在psycopg2中设置transaction \query timeout?

编程入门 行业动态 更新时间:2024-10-24 10:15:03
本文介绍了在psycopg2中设置transaction \query timeout?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

是否有办法在数据库事务或数据库查询中为 psycopg2 设置超时?

一个示例用例: Heroku将django web请求限制为30秒,之后Heroku终止请求而不允许django优雅地回退尚未返回的任何交易。这可能会在postgres上打开未完成的交易。您可以在数据库中配置超时,但这也会限制非Web相关的查询,如维护脚本分析等。在这种情况下,通过中间件设置超时( 您可以将超时设置为连接时间使用选项参数。语法有点奇怪:

>>> import psycopg2 >>> cnn = psycopg2.connect(dbname = test options =' - c statement_timeout = 1000')>>> cur = cnn.cursor()>>> cur.execute(select pg_sleep(2000)) Traceback(最近一次调用的最后一次):在< module>中,第1行的文件< stdin> psycopg2.extensions.QueryCanceledError:由于语句超时取消语句

它也可以被设置使用env变量:

>>> import os >>> os.environ ['PGOPTIONS'] ='-c statement_timeout = 1000'>>> import psycopg2 >>> cnn = psycopg2.connect(dbname = test)>>> cur = cnn.cursor()>>> cur.execute(select pg_sleep(2000)) Traceback(最近一次调用的最后一次):在< module>中,第1行的文件< stdin> psycopg2.extensions.QueryCanceledError:由于语句超时取消语句

Is there a way to set a timeout in psycopg2 for db transactions or for db queries?

A sample use-case: Heroku limits django web requests to 30sec, after which Heroku terminates the request without allowing django to gracefully roll-back any transactions which have not yet returned. This can leave outstanding transactions open on postgres. You could configure a timeout in the database, but that would also limit non-web-related queries such as maintenance scripts analytics etc. In this case setting a timeout via the middleware (or via django) would be preferable.

解决方案

You can set the timeout at connection time using the options parameter. The syntax is a bit weird:

>>> import psycopg2 >>> cnn = psycopg2.connect("dbname=test options='-c statement_timeout=1000'") >>> cur = cnn.cursor() >>> cur.execute("select pg_sleep(2000)") Traceback (most recent call last): File "<stdin>", line 1, in <module> psycopg2.extensions.QueryCanceledError: canceling statement due to statement timeout

it can also be set using an env variable:

>>> import os >>> os.environ['PGOPTIONS'] = '-c statement_timeout=1000' >>> import psycopg2 >>> cnn = psycopg2.connect("dbname=test") >>> cur = cnn.cursor() >>> cur.execute("select pg_sleep(2000)") Traceback (most recent call last): File "<stdin>", line 1, in <module> psycopg2.extensions.QueryCanceledError: canceling statement due to statement timeout

更多推荐

在psycopg2中设置transaction \query timeout?

本文发布于:2023-10-16 12:13:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1497520.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:transaction   timeout   query

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!