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)

你可能感兴趣的:(flask的路由中使用线程遇到的问题)