¿Configurar el tiempo de espera de consulta / comando con sqlalchemy create_engine?

El siguiente fragmento de código de Python ilustra el problema:

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

Puede establecer valores de configuración como statement_timeout través del parámetro options en libpq . Puede acceder a este parámetro en psycopg2 como parte de la llamada de connect . Puede pasar parámetros adicionales a la llamada de connect desde SQLAlchemy a través del parámetro connect_args . Entonces, juntándolo todo:

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