Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/345.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何设置查询执行的语句超时_Python_Postgresql_Sqlalchemy - Fatal编程技术网

Python 如何设置查询执行的语句超时

Python 如何设置查询执行的语句超时,python,postgresql,sqlalchemy,Python,Postgresql,Sqlalchemy,在我的web应用程序中,一些postgres sql查询需要很长时间才能执行。 我只想为其中的一部分设置语句超时 查询的一部分必须在超时前取消,但另一部分必须在没有任何限制的情况下工作 postgres exist语句中的超时函数 如何使用语句\超时函数包装SqlAlchemy查询 像这样: SET statement_timeout TO 1000; -- timeout for one second <sqlalchemy generated query>; RESET stat

在我的web应用程序中,一些postgres sql查询需要很长时间才能执行。 我只想为其中的一部分设置语句超时

查询的一部分必须在超时前取消,但另一部分必须在没有任何限制的情况下工作

postgres exist语句中的超时函数

如何使用语句\超时函数包装SqlAlchemy查询

像这样:

SET statement_timeout TO 1000; -- timeout for one second
<sqlalchemy generated query>;
RESET statement_timeout; -- reset
SqlAlchemy必须:1)设置语句超时2)执行查询并返回结果3)重置当前会话的语句超时

是否可以通过其他方式设置查询执行超时

更新1。我的解决方案

我的解决方案是一个自定义连接代理(使用psycopg2==2.4和SQLAlchemy==0.6.6进行测试):

此解决方案无需重置语句\u超时,因为每个SqlAlchemy查询都在独立事务中执行,并且 在当前事务中定义的语句\u超时

使用示例(超时pаram,以秒为单位):


您应该看看SQLAlchemy提供的扩展,第一个链接已断开
users = session.query(User).timeout(0.5).all()
from sqlalchemy.interfaces import ConnectionProxy

class TimeOutProxy(ConnectionProxy):
    def cursor_execute(self, execute, cursor, statement, parameters, context, executemany):

        timeout = context.execution_options.get('timeout', None)

        if timeout:
            c = cursor._parent.cursor()
            c.execute('SET statement_timeout TO %d;' % int(timeout * 1000))
            c.close()

        return execute(cursor, statement, parameters, context)


engine = create_engine(URL, proxy=TimeOutProxy(), pool_size=1, max_overflow=0)
Session.query(Author).execution_options(timeout=0.001).all()

Session.bind.execute(text('select * from author;') \
      .execution_options(timeout=0.001)) \
      .fetchall()