Psycopg2 Postgre 连接重试

Psycopg2 Postgre Connection retries

我正在尝试在 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

行:

 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.

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

来自官方使用文档:

For positional variables binding, the second argument must always be a sequence, even if it contains a single variable. And remember that Python requires a comma to create a single element tuple