Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to preserve database connection in a python web server

I am looking at the Flask tutorial, and it suggests to create a new database connection for each web request. Is it the right way to do things ? I always thought that the database connection should only once be created once for each thread. Can that be done, while maintaining the application as thread-safe, with flask, or other python web servers.

like image 733
Pankaj Avatar asked Jul 14 '11 04:07

Pankaj


People also ask

Do we need to close DB connection in python?

It does close the cursor, but it usually is not necessary because the same happens automatically when csr goes out of scope (and that is usually soon enough). Use it only if you want to remove csr from the namespace and/or reduce references to the object by one.

Which method is used to close database connection in python?

To disconnect Database connection, use close() method. If the connection to a database is closed by the user with the close() method, any outstanding transactions are rolled back by the DB.


2 Answers

For learning purposes maybe yes. But in a real application running on a production environment that is not an ideal situation at all.

Normally, you would always want to have a connection pool between your application and the database. No matter what language/database you are using this is a common solution.

A database connection pool maintains open a number of connections. The application layer simply takes a connection that is not being used, the connections get released when the application layer doesn't need them anymore. By "released" I mean that they get returned to the pool in order to be used again.

Bottom line, connections are not open/close per request. They get acquired/released from/to the database connection pool.

For instance, with Python and mysql you could go for PySQLPool.

like image 78
Manuel Salvadores Avatar answered Oct 18 '22 10:10

Manuel Salvadores


Is creating a new connection each request the way to go? No. For large applications we strongly recommend using SQLAlchemy (which can have a connection pool configured), even if you are not interested in the ORM. The docs have a section on that actually: http://flask.pocoo.org/docs/patterns/sqlalchemy/#sql-abstraction-layer

like image 36
Armin Ronacher Avatar answered Oct 18 '22 08:10

Armin Ronacher