Fhuad Balogun
Fhuad Balogun

Reputation: 67

psycopg2.InterfaceError: connection already closed on FastAPI

I followed the answer here to create a connection using psycopg2. It works on the first call on the endpoint. The second try gives this error psycopg2.InterfaceError: connection already closed. Below is a snippet of my code:

from config import conn
    with conn:
        with conn.cursor() as cursor:
            cursor.execute("""
            select ... 
            """
            )
            pos = cursor.fetchone()

            cursor.execute("""
            select ...' 
            """
            )
            neg = cursor.fetchone()

    conn.close()

Upvotes: 1

Views: 9982

Answers (1)

patkru
patkru

Reputation: 110

Since you're closing the connection in the last line of your code, it cannot be used further (when calling the endpoint for the second time) without reconnecting.

You can either delete the last line (which would result in never closing connection) and move conn.close() to app shutdown event or perform psycopg2.connect each time you need it.

Upvotes: 1

Related Questions