【问题标题】:Python psycopg2 timeoutPython psycopg2 超时
【发布时间】:2015-02-22 20:34:42
【问题描述】:

我有一个大问题: 运行我的 python 软件的服务器的路由器上似乎存在一些硬件问题。只有大约每三次才能成功连接到数据库。因此,psycopg2.connect() 最多可能需要 5 分钟才能得到超时异常。

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

这就是我正在使用的代码。

# 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)

我为查询尝试了一些超时添加,但没有帮助,因为连接根本没有建立。

有没有办法,当连接无法建立时,我可以立即停止程序?

【问题讨论】:

  • 可能被某种应用防火墙阻止了?

标签: python postgresql connection timeout psycopg2


【解决方案1】:

当对connect 函数使用关键字参数语法时,可以使用任何libpd 支持的连接参数。其中有connect_timeout 秒:

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 异常。

【讨论】:

  • 先发表评论,尽管这可能值得提出新问题:在我的情况下,我得到了超时,以及这个提示:Is the server running on host "xxxxxx.xxxxxx.us-west-1.rds.amazonaws.com" (xx.x.xxx.xxx) and accepting TCP/IP connections on port 5432?。答案确实是肯定的。事实上,我可以在同一个工具的节点变体中建立连接,但仍然无法通过我编写的psycopg2 版本进行连接。
  • 如果你能做到psql "some connection string" 那么psycopg2.connect(dsn="some connection string" ) 也应该可以工作。
  • PGOPTIONS 中的超时选项与作为 libpq 连接参数一部分的超时选项有什么区别?
猜你喜欢
  • 2019-03-07
  • 1970-01-01
  • 2017-12-29
  • 2013-11-26
  • 2022-12-03
  • 1970-01-01
  • 2020-05-31
  • 2015-08-06
  • 1970-01-01
相关资源
最近更新 更多