Set database connection timeout in Python

前端 未结 4 1283
情歌与酒
情歌与酒 2020-12-10 04:48

I\'m creating a RESTful API which needs to access the database. I\'m using Restish, Oracle, and SQLAlchemy. However, I\'ll try to frame my question as generically as possi

相关标签:
4条回答
  • 2020-12-10 05:10

    Timing Out with the System Alarm

    Here's how to use the operating system timout to do this. It's generic, and works for things other than 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!!
    
    0 讨论(0)
  • 2020-12-10 05:15

    for the query, you can look on timer and conn.cancel() call.

    something in those lines:

    t = threading.Timer(timeout,conn.cancel)
    t.start()
    cursor = conn.cursor()
    cursor.execute(query)
    res =  cursor.fetchall()
    t.cancel()
    
    0 讨论(0)
  • 2020-12-10 05:29

    You could look at setting up PROFILEs in Oracle to terminate the queries after a certain number of logical_reads_per_call and/or cpu_per_call

    0 讨论(0)
  • 2020-12-10 05:33

    In linux see /etc/oracle/sqlnet.ora,

    sqlnet.outbound_connect_timeout= value

    also have options:

    tcp.connect_timeout and sqlnet.expire_time, good luck!

    0 讨论(0)
提交回复
热议问题