sqlalchemy:停止长时间运行的查询 [英] sqlalchemy: stopping a long-running query
问题描述
我看似直截了当,但是找不到简单的解决方案。
我正在使用sqlalchemy查询postgres。如果客户端超时,我想从另一个线程停止/取消长时间运行的postgres查询。线程有权访问Session或Connection对象。
这时我已经尝试过:
session.bind .raw_connection()。close()
和
session.connection()。close()
和
session.close
和
session.transaction.close()
但是无论我如何尝试,postgres查询仍将继续直到结束。我从顶部看pg就知道这一点。这不是很容易做到吗?我想念什么吗?
到目前为止,这似乎很好用:
p>
def test_close_connection(self):
从psycopg2.extensions导入QueryCanceledError
从sqlalchemy导入.exc import DBAPIError
session = Session()
conn = session.connection()
sql = self.get_raw_sql_for_long_query()
seconds = 5
t = threading.Timer(seconds,conn.connection.cancel)
t.start()
try:
conn.execute(sql)
除了DBAPIError,e:
if type(e.orig)== QueryCanceledError:
print'长期运行的查询被取消。'
t.cancel()
I have a seemingly straight-forward situation, but can't find a straight-forward solution.
I'm using sqlalchemy to query postgres. If a client timeout occurs, I'd like to stop/cancel the long running postgres queries from another thread. The thread has access to the Session or Connection object.
At this point I've tried:
session.bind.raw_connection().close()
and
session.connection().close()
and
session.close
and
session.transaction.close()
But no matter what I try, the postgres query still continues until it's end. I know this from watching pg in top. Shouldn't this be fairly easy to do? I'm I missing something? Is this impossible without getting the pid and sending a stop signal directly?
This seems to work well, so far:
def test_close_connection(self):
import threading
from psycopg2.extensions import QueryCanceledError
from sqlalchemy.exc import DBAPIError
session = Session()
conn = session.connection()
sql = self.get_raw_sql_for_long_query()
seconds = 5
t = threading.Timer(seconds, conn.connection.cancel)
t.start()
try:
conn.execute(sql)
except DBAPIError, e:
if type(e.orig) == QueryCanceledError:
print 'Long running query was cancelled.'
t.cancel()
这篇关于sqlalchemy:停止长时间运行的查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!