简体   繁体   中英

Psycopg2 Postgre Connection retries

I'm trying to write a little webservice in Python. I use Heroku and their postgre-DB Service (free).

But I encountered a small but really annoying problem. When I try to search for something in the Database, the program connects to the database but keeps on trying, even though it worked the first time.

The part calling the search_image function:

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

The connect_to_database function:

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

The search_image function:

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"

This here is how the log looks as soon, as the handle_send function gets called: http://i.stack.imgur.com/pTZcF.png

What is the problem here?
This is my first proper program written in Python so if this is an obvious error I'm sorry :S

The line:

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

... will check if DATABASE_URL doesn't exist and then checks __is_connected == True (which is true after the first connection).

Hence on each subsequent check your program is going to print("Environment-variable missing or already connected") because every run evaluates if __is_connected == True .

You should consider breaking it down a little further:

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.

Ok I found the error. The execute function NEEDS a tuple as second argument.

From the official usage documentation:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM