使用sqlalchemy create_engine配置查询/命令超时?

时间:2017-07-05 21:48:04

标签: python sqlalchemy

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

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

1 个答案:

答案 0 :(得分:7)

您可以通过statement_timeout设置options parameter in libpq等配置值。您可以psycopg2作为connect调用的一部分在connect中访问此参数。您可以通过connect_args参数将其他参数传递给SQLAlchemy的engine = create_engine(..., connect_args={"options": "-c statement_timeout=1000"}) 调用。所以,把它们放在一起:

decay_rate = 0.99 # decay factor for RMSProp leaky sum of grad^2