Django如何在DatabaseError后重新连接:查询超时 [英] Django how to reconnect after DatabaseError: query timeout
问题描述
我有一个独立的脚本使用Django ORM从/到Postgre读/写。
I have a stand-alone script that reads/writes from/to Postgre using Django ORM.
我偶尔会遇到这个错误
DatabaseError:查询超时服务器
意外关闭连接
这可能意味着服务器在处理请求之前或之前异常终止
。 / p>
DatabaseError: query timeout server closed the connection unexpectedly This probably means the server terminated abnormally before or while processing the request.
我需要重新建立连接并在脚本中重试处理代码,但似乎找不到一种方法。以下代码在重试时引发InterfaceError:connection already closed,因此无法正常工作。
I need to re-establish the connection and retry the processing code in the script, but can't seem to find a way. The following code raises 'InterfaceError: connection already closed' on retry, so it doesn't work.
for repeat in range(5):
try:
.....................PROCESSING CODE...................
except DatabaseError, e:
time.sleep(30)
else:
break
else:
return
任何想法?
推荐答案
我有类似的需要重新创建数据库连接,我尝试以下黑魔法重置django 1.3中的连接:
I have a similar need for recreating the database connection and I'm trying the following black magic to reset the connection in django 1.3:
from django.db import connection
connection.connection.close()
connection.connection = None
我没有PostgreSQL方便的尝试,但它似乎至少适用于MySQL和sqlite。此外,如果您使用多数据库,您必须从django.db.connections字典对您的特定连接执行此步骤。
I don't have PostgreSQL handy to try this out, but it seems to work for MySQL and sqlite at least. Also, if you're using multi-db, you're going to have to perform this step on your specific connection from the django.db.connections dictionary.
这篇关于Django如何在DatabaseError后重新连接:查询超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!