set transaction\query timeout in psycopg2?

后端 未结 3 1867
甜味超标
甜味超标 2020-12-15 05:32

Is there a way to set a timeout in psycopg2 for db transactions or for db queries?

A sample use-case:
Heroku limits django web requests to 30sec

3条回答
  •  独厮守ぢ
    2020-12-15 05:34

    You can set the timeout at connection time using the options parameter. The syntax is a bit weird:

    >>> import psycopg2
    >>> cnn = psycopg2.connect("dbname=test options='-c statement_timeout=1000'")
    >>> cur = cnn.cursor()
    >>> cur.execute("select pg_sleep(2000)")
    Traceback (most recent call last):
      File "", line 1, in 
    psycopg2.extensions.QueryCanceledError: canceling statement due to statement timeout
    

    it can also be set using an env variable:

    >>> import os
    >>> os.environ['PGOPTIONS'] = '-c statement_timeout=1000'
    >>> import psycopg2
    >>> cnn = psycopg2.connect("dbname=test")
    >>> cur = cnn.cursor()
    >>> cur.execute("select pg_sleep(2000)")
    Traceback (most recent call last):
      File "", line 1, in 
    psycopg2.extensions.QueryCanceledError: canceling statement due to statement timeout
    

提交回复
热议问题