Flask tutorial: Why do we use the app context for the DB connection?

Viewed 2116

I'm studying the Flask tutorial and am confused about the usage of the app context for connecting to the database. On the page, the author says:

Creating and closing database connections all the time is very inefficient, so you will need to keep it around 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 seems that creating and closing the connection is exactly what is accomplished by the code. We have a view get_db that connects to the database, returns a connection object, and adds it to the app context if not present. We also have a close_db view that closes the connection object when the app context is torn down.

My understanding of what's happening here is as follows: A user connects to the app's home page, establishing a connection with the database and then closing it. Each time the user makes a request to the page (e.g., posting a new blog entry), a new connection is established with the database and then closed when the request is completed. So what's the value of using the app context at all? Why not just directly create and close a connection for each request?

Maybe I am misunderstanding something here -- any insight appreciated!

1 Answers
Related