【问题标题】:Psycopg2 Postgre Connection retriesPsycopg2 Postgres 连接重试
【发布时间】:2015-07-16 07:10:27
【问题描述】:

我正在尝试用 Python 编写一个小网络服务。我使用 Heroku 和他们的 postgre-DB 服务(免费)。

但是我遇到了一个小但很烦人的问题。当我尝试在数据库中搜索某些内容时,程序会连接到数据库,但会继续尝试,即使它第一次运行也是如此。

调用search_image函数的部分:

def handle_send(update):
    link = databasecon.search_image(update["message"]["text"], update)

connect_to_database 函数:

def connect_to_db():
    global __is_connected
    if "DATABASE_URL" not in os.environ or __is_connected == True:
        print("Environment-variable missing or already connected")
    else:
        urllib.parse.uses_netloc.append("postgres")
        url = urllib.parse.urlparse(os.environ["DATABASE_URL"])
        con = psycopg2.connect(
            database=url.path[1:],
            user=url.username,
            password=url.password,
            host=url.hostname,
            port=url.port
            )
        if con != None:
            __is_connected = True
    return con

search_image 函数:

def search_image(image_name, update):
    db_con = connect_to_db()
    cur = db_con.cursor()
    query = """select link from mm_image where id=%s"""
    cur.execute(query, (image_name))
    result = cur.fetchone()
    if result != None:
        image_link = str(result[0])
        disconnect_from_db(db_con)
        return image_link
    else:
        disconnect_from_db(db_con)
        return "Not found"

这就是调用 handle_send 函数后日志的外观: http://i.stack.imgur.com/pTZcF.png

这里有什么问题?
这是我第一个用 Python 编写的正确程序,所以如果这是一个明显的错误,我很抱歉:S

【问题讨论】:

    标签: python database postgresql heroku psycopg2


    【解决方案1】:

    行:

     if "DATABASE_URL" not in os.environ or __is_connected == True:
            print("Environment-variable missing or already connected")
        else:
    

    ... 将检查 DATABASE_URL 是否不存在,然后检查 __is_connected == True(在第一次连接后 为真)。

    因此,在每次后续检查中,您的程序都会转到 print("Environment-variable missing or already connected"),因为每次运行都会评估 if __is_connected == True

    你应该考虑进一步分解它:

    def connect_to_db():
        global __is_connected
        if __is_connected == True:
            break;
        elif "DATABASE_URL" not in os.environ:
            print("DATABASE_URL not set")
        else:
            print("
            urllib.parse.uses_netloc.append("postgres")
            url = urllib.parse.urlparse(os.environ["DATABASE_URL"])
            con = psycopg2.connect
            // etc.
    

    【讨论】:

    • 嘿,看起来好像我没有正确描述我的问题。我遇到的问题是,当handle_send 被调用并尝试连接到数据库时,它会以某种方式在连接上启动一个循环,并多次重试连接到数据库,直到我强制停止程序。然后看起来像这样:puu.sh/j1fdq/7d0fe34e34.PNG(一旦我写了“heytest.gif”-Message,程序就会调用 handle_send-function。)
    【解决方案2】:

    好的,我发现了错误。执行函数需要一个元组作为第二个参数。

    来自官方使用文档:

    对于位置变量绑定,第二个参数必须始终是一个序列,即使它包含单个变量。请记住,Python 需要逗号来创建单个元素元组

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-31
      • 2020-10-09
      • 2019-05-05
      • 1970-01-01
      • 2019-12-14
      • 1970-01-01
      • 2020-03-27
      相关资源
      最近更新 更多