简体   繁体   English

sqlite同时多次写入

[英]sqlite multiple writes at same time

i'm making a python flask app with sqlite database is there a way to make a queue for write requests so that it can run smoothly AS SQLITE doesn't support multiple concurrent writes or commits我正在使用 sqlite 数据库制作一个 python flask 应用程序,有没有办法为写请求创建一个队列,以便它可以顺利运行,因为 SQLITE 不支持多个并发写入或提交

this is my connection string这是我的连接字符串

engine = create_engine('sqlite:///IT_DataBase.db',
                       connect_args={'check_same_thread': False})
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
session = DBSession()

and this is the commit code as example:这是作为示例的提交代码:

@app.route('/NewRequest', methods=['GET', 'POST'])
@login_required
def NewRequest():
    connUser=session.query(User).filter(User.id==Session.get('user_id')).one()
    if request.method == 'GET':
        Types = session.query(Req_Type.id,Req_Type.Type_name)
        Pr = session.query(Req_Priorities.id,Req_Priorities.Priority_name)
        return render_template('NewRequest.html',conn=connUser ,name=current_user.name, items=Types,priorities=Pr)
    else:
        name= request.form['Name']
        Description= request.form['Description']
        Type = request.form.get('Type')
        Priority = request.form.get('Priority')
        newRequest = Requests(name=name, Record_Created=datetime.now().strftime("%Y-%m-%d %H:%M"), Description=Description, Assigned_To=None, Type_Name=str(Type), Priority_Name=str(Priority), Status_Name='Opened', User_ID=Session.get('user_id') )
        session.add(newRequest)
        flash('New Request With Name %s Successfully Created' % newRequest.name)
        session.commit()
        UserRequests= session.query(Requests).filter_by(User_ID=Session.get('user_id')).filter(Requests.Status_Name!='Solved').all()
        return render_template('ReqData.html',conn=connUser , title='User Requests', rows=UserRequests)

i think that if we didn't change the database engine the solution is either to queue the commits but i don't know how or to make flask wait random time before commiting but i think this will make performance poor what should i do我认为,如果我们不更改数据库引擎,解决方案要么是将提交排队,但我不知道如何或让 Flask 在提交前等待随机时间,但我认为这会使性能变差我该怎么办

You need to serialize the commits.您需要序列化提交。 Create a lock like below.创建一个如下所示的锁。

from threading import RLock

sql_lock = RLock()

Wrap session.add and session.commit like the following.像下面这样包装 session.add 和 session.commit。 lock.acquire() will block the code while another thread has acquired the lock, and is yet to release the lock. lock.acquire()将阻塞代码,而另一个线程已获取锁,但尚未释放锁。 This ensures that only one thread (or none) is running between acquire() and release() at all times.这确保了在任何时候都只有一个线程(或没有线程)在acquire()release()之间运行。

    try:
        sql_lock.acquire()
        session.add(newRequest)
        session.commit()
    finally:
        sql_lock.release()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM