Flask Tutorial: Why We Use Application Context to Connect to DB?

I am studying Flask Tutorial and am confused about using application context to connect to database. On the page, the author says:

Making and closing database connections is very inefficient all the time, so you will need to maintain it for longer. Because database connections encapsulate a transaction, you will need to make sure that only one request at a time uses the connection.

However, it looks like creating and closing a connection is exactly what the code does. We have a view get_db

that connects to the database, returns a connection object, and adds it to the application context if it is missing. We also have a view close_db

that closes the connection object when the application context is dropped.

My understanding of what's going on here is this: the user connects to the application home page, establishes a connection to the database, and then closes it. Every time a user makes a request for the page (for example, publishes a new blog post), a new connection is established to the database and then closed when the request is complete. So what is the value of using application context? Why not just create and close a connection for every request?

Maybe I am misunderstanding something here - any understanding is appreciated!

+3


source to share


1 answer


This is poorly documented. But basically the meaning of an application context is in abstract data objects specific to the application, but in constant cross-request (ostensibly for permissions of applications with multiple tenants that are separate instances Flask

, without binding everything to request the context). In any case, flask.g

is the application-specific context for the current application context. This way you can call get_db()

on the first request, drag the resulting connection object into g

, and then use g.dbconn

later in the application, which won't get killed on every request (presumably you want to use the same connection for every page access). I like to think aboutflask.g

as in the example (sample application, in this case) globals()

.



See also: http://flask.pocoo.org/docs/0.12/appcontext/#app-context

+3


source







All Articles