How to preserve database connection in a python web server

后端 未结 3 905
滥情空心
滥情空心 2020-12-25 14:22

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 da

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-25 15:06

    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.

提交回复
热议问题