python MySQLDB query timeout

后端 未结 6 1999
误落风尘
误落风尘 2020-12-24 09:45

I\'m trying to enforce a time limit on queries in python MySQLDB. I have a situation where I have no control over the queries, but need to ensure that they do not run over a

6条回答
  •  猫巷女王i
    2020-12-24 10:16

    @nosklo's twisted-based solution is elegant and workable, but if you want to avoid the dependency on twisted, the task is still doable, e.g:

    import multiprocessing
    
    def query_with_timeout(dbc, timeout, query, *a, **k):
      conn1, conn2 = multiprocessing.Pipe(False)
      subproc = multiprocessing.Process(target=do_query,
                                        args=(dbc, query, conn2)+a, 
                                        kwargs=k)
      subproc.start()
      subproc.join(timeout)
      if conn1.poll():
        return conn1.recv()
      subproc.terminate()
      raise TimeoutError("Query %r ran for >%r" % (query, timeout))
    
    def do_query(dbc, query, conn, *a, **k):
      cu = dbc.cursor()
      cu.execute(query, *a, **k)
      return cu.fetchall()
    

提交回复
热议问题