SQlite3 上下文管理器在 python 2.7 中锁定文件 [英] SQlite3 context manager with file locking in python 2.7
本文介绍了SQlite3 上下文管理器在 python 2.7 中锁定文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是在 Python 2.7 下的上下文管理器中通过重新进入进行文件锁定的好方法吗?我只是想确保 rlock() 会有效,以便我可以让多线程应用程序使用单个数据库文件.
Is this the good way to do file locking with re-entrance in a context manager under Python 2.7? I just want to be sure the rlock() is going to be effective so I could get a multi-threaded application to use a single database file.
import sqlite3
import threading
import os
class ConnectionHolder:
def __init__(self, connection):
self.path = connection
self.lock = threading.RLock()
def __enter__(self):
self.lock.acquire()
self.connection = sqlite3.connect(self.path)
self.cursor = self.connection .cursor()
return self.cursor
def __exit__(self, exc_class, exc, traceback):
self.connection .commit()
self.connection .close()
self.lock.release()
conn_holder = ConnectionHolder(os.path.join(os.path.dirname(__file__), 'data/db/database.db'))
if __name__ == '__main__':
with conn_holder as c:
c.execute("SELECT * FROM 'sample_table'")
result = c.fetchall()
print result
推荐答案
我终于喜欢在我的代码中一个地方,我在提交之前运行了一个长循环(大约 2 分钟).我更正了这一点,并按照@DB 的建议,将繁忙超时增加到 30 秒.问题似乎解决了.谢谢各位!
I finally fond in my code a place where I was running a long loop (about 2 minutes) before commiting. I correct this and, as @DB suggested, increase busy timeout to 30 seconds. Problem seem to be resolved. Thanks guys!
这篇关于SQlite3 上下文管理器在 python 2.7 中锁定文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文