Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How teardown_request() works with Python- Flask?

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?

like image 576
webminal.org Avatar asked May 29 '15 04:05

webminal.org


People also ask

How do you process incoming request data in Flask?

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.

How can a request context be created in Flask Python?

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.

How do you use async in Flask?

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.


1 Answers

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

like image 122
junnytony Avatar answered Oct 10 '22 15:10

junnytony