1

Hi from the documentation it says that the connection will not close with the psycopg2 cursor when used with a context manager (which typically does that for us).

However, the results are quite different for a function im currently using, can someone explain why my decorator is being told that the cursor is already closed when using it with a context manager? When using it without the context manager, i face no such issue.

w/o context manager it requires the connection to close

w/ context manager it doesnt require the connection to close?

Here's the code:

import psycopg2
conn = "Your connection details"
def with_connection(func):
    """
    Function decorator for passing connections
    """
    def _connection(*args, **kwargs):
        with psycopg2.connect(conn) as connection:
#         connection = psycopg2.connect(conn)
            try:
                rv = func(connection, *args, **kwargs)
            except Exception as e:
                connection.rollback()
                raise e
            else:
                connection.commit()
            finally:
                connection.close()
        return rv
    return _connection

@with_connection
def run_sql(connection):
    result = []
    with connection.cursor() as cursor:
        cursor.execute("Select * FROM testing_owner")
        colnames = [desc[0] for desc in cursor.description]
        rows = cursor.fetchall()
        for row in rows:
            result.append(create_record(row, colnames))
    return result

run_sql()
----------------------------------------------------------------
InterfaceError                            Traceback (most recent call last)
/var/folders/mv/l927xbbd3q57zgr07vjlk5fr0000gn/T/ipykernel_5002/3317028511.py in <module>
     35     return result
     36 
---> 37 run_sql()

/var/folders/mv/l927xbbd3q57zgr07vjlk5fr0000gn/T/ipykernel_5002/3317028511.py in _connection(*args, **kwargs)
     20                 connection.commit()
     21             finally:
---> 22                 connection.close()
     23         return rv
     24     return _connection
InterfaceError: connection already closed
KiatHao
  • 11
  • 2

0 Answers0