python - 使用 Python 在 HTTP 服务器中进行基本锁定
问题描述
我正在实现一个基本的 HTTP 服务器,它通过 PostGRESQL 询问数据库。为了处理多个请求,我需要在服务器中为每个请求创建一个线程,我目前正在这样做。
class MyServer(ThreadingMixIn, HTTPServer):
def __init__(self, server_address, handler_class):
super().__init__(server_address=server_address, RequestHandlerClass=handler_class)
self.KEEP_ALIVE = True
def run(self):
while self.KEEP_ALIVE:
self.handle_request()
例如,我的 do_DELETE 方法是这样完成的:
def do_DELETE(self):
# Get ID from the request path
config_id = self.path[2:]
# Connect to DB
connection_db, cursor = self.connect_to_DB()
with connection_db:
# Check if the config to delete exists
cursor.execute('SELECT * FROM configuration WHERE id=%s', (config_id, ))
res = cursor.fetchall()
# If the config to delete exists, the operation is done. Otherwise an error message is sent back
if len(res) != 0:
cursor.execute('DELETE FROM configuration WHERE id=%s', (config_id,))
response_code = 200
answer = OPERATION_SUCCESSFUL
else:
# Send error message back
response_code = 400
answer = NO_SUCH_ID_ERROR
content_type = 'text/plain'
self.reply(response_code=response_code, content_type=content_type, answer=answer)
我想这样做,在 do_DELETE 方法中,对数据库的两个查询的部分是原子的,即它应该锁定所有线程可见的资源......但我不知道该怎么做它。你能帮助我吗?