Python psycopg2 timeout(Python psycopg2 超时)
问题描述
我有一个大问题:运行我的 python 软件的服务器的路由器上似乎存在一些硬件问题.只有大约每三次才能成功连接到数据库.因此,psycopg2.connect() 最多可能需要 5 分钟才能获得超时异常.
I have a huge problem: There seems to be some hardware problems on the router of the server my python software runs on. The connection to the database only is successfull about every third time. So a psycopg2.connect() can take up to 5 minutes before I get an timeout exception.
2014-12-23 15:03:12,461 - ERROR - could not connect to server: Connection timed out
Is the server running on host "172.20.19.1" and accepting
这就是我正在使用的代码.
That's the code I'm using.
# Connection to the DB
try:
db = psycopg2.connect(host=dhost, database=ddatabase,
user=duser, password=dpassword)
cursor = db.cursor(cursor_factory=psycopg2.extras.DictCursor)
except psycopg2.DatabaseError, err:
print(str(err))
logging.error(str(err))
logging.info('program terminated')
sys.exit(1)
我为查询尝试了一些超时添加,但没有帮助,因为连接根本没有建立.
I tried some timeout additions for the query, but that didn't helped, since the connection didn't got established at all.
有没有办法,当无法建立连接时,我可以立即停止程序?
Is there a way, I can stop the program immediately, when the connection couldn't be established?
推荐答案
在 connect
函数中使用关键字参数语法时,可以使用任何 libpd
支持的连接参数.其中有 connect_timeout
秒:
When using the keyword arguments syntax to the connect
function it is possible to use any of the libpd
supported connection parameters. Among those there is connect_timeout
in seconds:
db = psycopg2.connect (
host=dhost, database=ddatabase,
user=duser, password=dpassword,
connect_timeout=3
)
http://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-PARAMKEYWORDS
http://initd.org/psycopg/docs/module.html
连接超时引发 OperationalError
例外.
A connection time out raises an OperationalError
exception.
这篇关于Python psycopg2 超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python psycopg2 超时


基础教程推荐
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 筛选NumPy数组 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01