Flask, concurrent.futures and SQLAlchemy - No application found: work inside a view function or push an application context Flask, concurrent.futures and SQLAlchemy - No application found: work inside a view function or push an application context flask flask

Flask, concurrent.futures and SQLAlchemy - No application found: work inside a view function or push an application context


In case anyone who meet the same problem

from flask import current_appdef context_wrap(fn):    app_context = current_app.app_context()    def wrapper(*args, **kwargs):        with app_context:            return fn(*args, **kwargs)    return wrapper#Then In this case:future_to_track = {        executor.submit(context_wrap(build_cache)): 'TRACKER DONE'}#OR In your case:context_wrap(any_func_need_context)


The following worked:

def build_cache():    with app.app_context():        (...)def upload_cache(track):    with app.app_context():        (...)@app.route('/cache')def cache():    with app.app_context():        with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor:            (...)