Replies: 2 comments
-
A tread will never have the context of the parent that started it. You should create a new context (and a new connection) inside the thread, not outside it. That was true before 2.2 as well. def task(app):
with app.app_context():
time.sleep(2)
# do something with the database here
print(current_app.name)
@bp.route("/start", methods=["GET", "POST"])
def start():
app = current_app._get_current_object()
t = Thread(target=task, args=(app,))
t.start()
return "started" |
Beta Was this translation helpful? Give feedback.
-
The creation of a new context does not seem really mandatory or blocking, I have also no error message on this subject. It's the closing of the SQL connection that seems random, the threaded tasks run 1 time out of 3, they crash due to the absence of an SQL connection. I'm using your Flask-SqlAlchemy extension (through this simple statement: However, I found a small workaround that seems to fix these SQL reconnect issues this way: with app.app_context():
db.engine.connect() # + to avoid sql connection error Maybe this question should be reported on the Flask-SqlAlchemy repository, sorry. |
Beta Was this translation helpful? Give feedback.
-
It is no longer possible to launch a thread in the background which uses the database (since its connection is closed by the context of the application) despite the use
with app.app_context()
I got this kind of errors:
Is there another way to preserve the context in some cases?
I use ThreadPoolExecutor patched by gevent for processing tasks after a request.
Beta Was this translation helpful? Give feedback.
All reactions