使用sqlalchemy create_engine配置查询/命令超时? [英] Configure query/command timeout with sqlalchemy create_engine?

查看:917
本文介绍了使用sqlalchemy create_engine配置查询/命令超时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下Python代码片段说明了此问题:

The following Python code snippet illustrates the issue:

print("starting")

# I am trying to configure a query/command timeout of one second.
# sqlalchemy docs suggest execution_options but the documented list of options doesn't include a timeout:
# http://docs.sqlalchemy.org/en/latest/core/connections.html#sqlalchemy.engine.Connection.execution_options
# Below, I am guessing at several likely timeout parameter names:
db_engine = create_engine("postgresql://user:pass@server/catalog",
                          execution_options={"timeout": 1.0,
                                             "statement_timeout": 1.0,
                                             "query_timeout": 1.0,
                                             "execution_timeout": 1.0})

with db_engine.connect() as db_connection:
    print("got db_connection")

    # Artificially force a two second query time with pg_sleep.
    # This is designed to guarantee timeout conditions and trigger an exception.
    result_proxy = db_connection.execute("SELECT pg_sleep(2);")

    # If the timeout worked, this statement will not execute.
    # Currently, it does execute, which means my timeout isn't working.
    print("Query successfully complete. Got result_proxy")


推荐答案

您可以设置配置值,例如 statement_timeout 通过 libpq 中的选项参数。您可以作为 psycopg2 中访问此参数。 = noreferrer> connect 调用。您可以通过connect 调用。 #custom-dbapi-args rel = noreferrer> connect_args 参数。因此,将它们放在一起:

You can set configuration values like statement_timeout via the options parameter in libpq. You can access this parameter in psycopg2 as part of the connect call. You can pass additional parameters to the connect call from SQLAlchemy via the connect_args parameter. So, putting it all together:

engine = create_engine(..., connect_args={"options": "-c statement_timeout=1000"})

这篇关于使用sqlalchemy create_engine配置查询/命令超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆