Flask tutorial: Why do we use the app context for the DB connection?
It's badly documented. But basically the whole point of the app context is to abstract app-specific-but-persistent-across-request data objects (ostensibly to allow multi-tenant applications that are all separate instances of Flask
without tying everything to request context). In any case, flask.g
is the app context-specific dict for the current app context. This way you can call get_db()
on the very first request, shove the resulting connection object into g
and then use g.dbconn
later on in the app, which doesn't get killed on each request (presumably you want to use the same connection on each page access). I like to think of flask.g
is like a class (well the app, in this case) instance of globals()
.
See also: http://flask.pocoo.org/docs/0.12/appcontext/#app-context