I received internal error with message:
"TimeoutError: QueuePool limit of size 5 overflow 10 reached, connection timed out, timeout 30"
and searching online gave teardown_request() solution :
@app.teardown_request
def checkin_db(exc):
try:
print "Removing db session."
db.session.remove()
except AttributeError:
pass
Now timeout error is gone. But I didn't understand teardown_request completely, look like db.session.remove() will be invoked after every request ? or every error? Is it safe to use this code?
To access the incoming data in Flask, you have to use the request object. The request object holds all incoming data from the request, which includes the mimetype, referrer, IP address, raw data, HTTP method, and headers, among other things.
Flask automatically pushes a request context when handling a request. View functions, error handlers, and other functions that run during a request will have access to the request proxy, which points to the request object for the current request.
Async functions require an event loop to run. Flask, as a WSGI application, uses one worker to handle one request/response cycle. When a request comes in to an async view, Flask will start an event loop in a thread, run the view function there, then return the result.
teardown_request
registers a function to be called at the end of each request whether it was successful or an exception was raised. It is a good place to cleanup request scope objects like a database session/transaction. That is all your code sample is doing.
It is safe to use that code and db.session.remove()
will be called after every request (even if an exception occurs during the request)
See Flask Callbacks and Errors and Flask.teardown_request for more information
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With