【问题标题】:Configure query/command timeout with sqlalchemy create_engine?使用 sqlalchemy create_engine 配置查询/命令超时?
【发布时间】:2017-12-09 17:31:36
【问题描述】:

以下 Python 代码 sn-p 说明了这个问题:

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

【问题讨论】:

    标签: python postgresql sqlalchemy


    【解决方案1】:

    您可以通过options parameter in libpq 设置statement_timeout 等配置值。作为connect 调用的一部分,您可以在psycopg2 中访问此参数。您可以通过 connect_args 参数从 SQLAlchemy 将其他参数传递给 connect 调用。所以,把它们放在一起:

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

    【讨论】:

    • 我不能用 mysql 做到这一点。我在 mysql 文档中找不到关于语句超时的任何地方。
    • @Dilip MySQL 的功能更加有限,但最接近的等价物(仅适用于只读SELECT 语句)是max_execution_time
    【解决方案2】:

    我花了一些时间才弄清楚如何使用 create_engine(...) 设置多个选项。以防万一,您也在寻找相同的 -

    engine = create_engine(..., connect_args={'options': '-c lock_timeout=3000 -c statement_timeout=3000'})
    

    【讨论】:

      猜你喜欢
      • 2021-10-11
      • 2021-03-11
      • 2016-07-06
      • 1970-01-01
      • 2022-07-19
      • 2019-10-30
      • 2017-09-26
      • 2015-03-26
      相关资源
      最近更新 更多