python - 心理学/Postgres : Connections hang out randomly

标签 python postgresql cherrypy psycopg2

我将 psycopg2 用于我目前正在开发的 cherrypy 应用程序,并使用 cli 和 phpgadmin 手动处理一些操作。这是 Python 代码:

#One connection per thread
cherrypy.thread_data.pgconn = psycopg2.connect("...") 
...
#Later, an object is created by a thread :
class dbobj(object):
 def __init__(self):
  self.connection=cherrypy.thread_data.pgconn
  self.curs=self.connection.cursor(cursor_factory=psycopg2.extras.DictCursor)
...
#Then,
try:
 blabla
 self.curs.execute(...)
 self.connection.commit()
except:
 self.connection.rollback()
 lalala
...
#Finally, the destructor is called :
def __del__(self):
 self.curs.close()

我在使用 psycopg 或 postgres 时遇到问题(尽管我认为后者更有可能)。在发送了一些查询之后,我的连接就断开了。同样,phpgadmin - 通常 - 也会被删除;在多次发出请求后,它会提示我重新连接。只有 CLI 保持不变。

问题是,这些都是随机发生的,我什至无法找出原因。我要么在几个页面请求后就被锁定,要么在请求了数百个页面后再也没有遇到任何问题。终止应用程序后,我在 postgres 日志中发现的唯一错误是:

...
LOG:  unexpected EOF on client connection
LOG:  could not send data to client: Broken pipe
LOG:  unexpected EOF on client connection
...

我想在每次创建新的 dbobj 实例时创建一个新连接,但我绝对不想这样做。

此外,我读到有人可能会遇到类似的问题,除非所有事务都已提交:我对每个 INSERT/UPDATE 查询都使用 try/except block ,但我从不将它用于 SELECT 查询,我也不想这样做编写更多样板代码(顺便说一句,它们需要提交吗?)。即使是这样,为什么 phpgadmin 会关闭?

max_connections 在 .conf 文件中设置为 100,所以我认为这也不是原因。一个 cherrypy worker 只有 10 个线程。

有人知道我应该先看哪里吗?

最佳答案

Psycopg2 需要在每个事务之后提交或回滚,包括 SELECT 查询,否则它会使连接“IDLE IN TRANSACTION”。现在这是文档中的警告:

Warning: By default, any query execution, including a simple SELECT will start a transaction: for long-running programs, if no further action is taken, the session will remain “idle in transaction”, an undesirable condition for several reasons (locks are held by the session, tables bloat...). For long lived scripts, either ensure to terminate a transaction as soon as possible or use an autocommit connection.

关于python - 心理学/Postgres : Connections hang out randomly,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4173168/

相关文章:

python - 将一个对象变异为它的子类的一个实例

python - 使用 Django Admin Actions 发送批量电子邮件

sql - PostgreSQL Order By 无法正常工作

python - 在 cherrypy/mako 中使用动态参数处理 URL

python - 像 python 控制台中的 ipython 一样默认制表符补全

python - 这里正在执行什么减法运算?

postgresql - Postgres 无法打开 CSV 文件进行读取访问 : Permission denied

sql - 具有许多产品类别的站点的数据库设计

python - 为授权编写 CherryPy 装饰器

jquery - Cherrypy调度