我正在创建一个需要访问数据库的RESTful API。我正在使用Restish,Oracle和SQLAlchemy。但是,我会尝试尽可能地设置我的问题,而不考虑Restish或其他Web API。
我希望能够为执行查询的连接设置超时。这是为了确保放弃长时间运行的查询,并丢弃(或回收)连接。此查询超时可以是全局值,这意味着,我不需要为每个查询或连接创建更改它。
给出以下代码:
import cx_Oracle
import sqlalchemy.pool as pool
conn_pool = pool.manage(cx_Oracle)
conn = conn_pool.connect("username/p4ss@dbname")
conn.ping()
try:
cursor = conn.cursor()
cursor.execute("SELECT * FROM really_slow_query")
print cursor.fetchone()
finally:
cursor.close()
如何修改上面的代码来设置查询超时?
此超时是否也适用于连接创建?
这类似于java.sql.Statement的setQueryTimeout(int seconds)方法在Java中的作用。
谢谢
对于查询,您可以查看计时器和conn.cancel()调用。
这些方面的东西:
t = threading.Timer(timeout,conn.cancel)
t.start()
cursor = conn.cursor()
cursor.execute(query)
res = cursor.fetchall()
t.cancel()
在linux中看到/etc/oracle/sqlnet.ora,
sqlnet.outbound_connect_timeout= value
也有选择:
tcp.connect_timeout和sqlnet.expire_time,祝你好运!
你可以看一下设置 简介在Oracle中,在一定数量的logical_reads_per_call和/或cpu_per_call之后终止查询
使用系统警报进行定时
以下是使用操作系统timout执行此操作的方法。它是通用的,适用于Oracle之外的其他东西。
import signal
class TimeoutExc(Exception):
"""this exception is raised when there's a timeout"""
def __init__(self): Exception.__init__(self)
def alarmhandler(signame,frame):
"sigalarm handler. raises a Timeout exception"""
raise TimeoutExc()
nsecs=5
signal.signal(signal.SIGALRM, alarmhandler) # set the signal handler function
signal.alarm(nsecs) # in 5s, the process receives a SIGALRM
try:
cx_Oracle.connect(blah blah) # do your thing, connect, query, etc
signal.alarm(0) # if successful, turn of alarm
except TimeoutExc:
print "timed out!" # timed out!!