3

I've read flask document and found this:

13.3 Locality of the Context

The application context is created and destroyed as necessary. It never moves between threads and it will not be shared between requests.

This is really odds to me. I think an app context should be persist with the app and share objects for all the requests of the app.

So I dive into the source code and find that when the request context is pushed , an application context will be created and pushed if current app is not the one the request associated with.

So it seems that the app context stack may have multiple different app context for the same app pushed? Why not using a singleton app context? Why the lifetime of the app context is so 'short'? What can be done for such app context?

Community
  • 1
  • 1
jayven
  • 770
  • 8
  • 19

1 Answers1

6

The app context is not meant for sharing between requests. It is there to share context before the request context is set up, as well as after the request has been torn down already. Yes, this means that there can be multiple g contexts active for different requests.

You can't share 'global' state because a WSGI app is not limited to a single process. Many WSGI servers use multiprocessing to scale request handling, not just threading. If you need to share 'global' state across requests, use something like a database or memcached.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Thanks for your answer. I know that app can be run under muli-process environment, for 'share objects' I mean a db connection pool in a process for example. If the app ctx is not for the purpose, where should I put the pool? And also can you give me an example what should be place in g? – jayven Nov 18 '15 at 13:18
  • `g` should be used for anything you share among different parts handling a request. For example, a `before_request` loading user data based on a request token, so that views and templates all can access this directly. For a database pool, just use a regular Python global; I strongly recommend using SQLAlchemy for this (even if you don't plan on using the ORM parts, the pool management options are second to none). – Martijn Pieters Nov 18 '15 at 14:17