博客 / 詳情

返回

flask的路由中使用線程遇到的問題

需要再路由中使用線程,線程中需要向mysql寫入數據。
使用了flask_sqlalchemy。
線程中是不能直接使用使用了flask_sqlalchemy的db對象的,因為線程中沒有flask的上下文環境。
在線程代碼中使用with app.appcontext()也是不行的。

from app import app, db
pool_executor = ThreadPoolExecutor(5)

def tesk1(data):
    with app.app_context():
        db.session.add()
        db.session.commit()

bp = Blueprint(...)

@bp.route(...)
def route1():
    pool_executor.submit(task1, data)

上面這樣使用app是不行的,current_app也是不行的。

必須要把app作為參數,傳遞給線程才可以。

from flask import current_app

pool_executor = ThreadPoolExecutor(5)

def tesk1(app, data):
    with app.app_context():
        db.session.add()
        db.session.commit()

bp = Blueprint(...)

@bp.route(...)
def route1():
    pool_executor.submit(task1, current_app._get_current_object(), data)
user avatar
0 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.