如何在python web服务器中保留数据库连接 [英] How to preserve database connection in a python web server

查看:266
本文介绍了如何在python web服务器中保留数据库连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在看Flask教程,它建议为每个Web请求创建一个新的数据库连接。这是做事的正确方法吗?我一直认为数据库连接应该只能为每个线程创建一次。可以这样做,同时保持应用程序为线程安全的,使用flask或其他python web服务器。

解决方案

目的可能是的。但是,在一个真正的应用程序上运行的生产环境根本不是一个理想的情况。

通常情况下,您总是希望在应用程序和数据库之间建立连接池。无论您使用何种语言/数据库,这都是一个常见的解决方案。

数据库连接池保持打开许多连接。应用程序层只需要一个未被使用的连接,当应用程序层不再需要时,连接就会被释放。 释放我的意思是他们回到池中以便再次使用。

底线,连接不是每个请求打开/关闭。它们从数据库连接池获取/释放。



例如,使用Python和mysql,您可以使用 PySQLPool


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.

解决方案

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.

这篇关于如何在python web服务器中保留数据库连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆