Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between application and request contexts?

Tags:

flask

Flask documentation says that there are 2 local context: application context, and request context. Both are created on request and torn down when it finishes.

So, what's the difference? What are the use cases for each? Are there any conditions when only one of these are created?

like image 435
kolypto Avatar asked Jan 05 '14 20:01

kolypto


1 Answers

Both are created on request and torn down when it finishes.

It is true in the request lifecycle. Flask create the app context, the request context, do some magic, destroy request context, destroy app context.

The application context can exist without a request and that is the reason you have both. For example, if I'm running from a shell, I can create the app_context, without the request and has access to the ´current_app` proxy.

It is a design decision to separate concerns and give you the option to not create the request context. The request context is expensive.

In old Flask's (0.7?), you had only the request context and created the current_app with a Werkzeug proxy. So the application context just create a pattern.

Some docs about appcontext, but you probably already read it: http://flask.pocoo.org/docs/appcontext/

like image 93
iurisilvio Avatar answered Oct 22 '22 22:10

iurisilvio