Using context managers for connections/cursors - cursors are closed, connections are not?

From: Victor Hooi <victorhooi(at)yahoo(dot)com>
To: psycopg(at)postgresql(dot)org
Subject: Using context managers for connections/cursors - cursors are closed, connections are not?
Date: 2013-11-27 00:24:34
Message-ID: CAMnnoUKDW3pjnTRdBL1vVctJhd3xqsZQG+2rDrrdyt3hzXeu7A@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: psycopg

Hi,

I'm trying to undersatnd

http://initd.org/psycopg/articles/2013/04/07/psycopg-25-released/

From

So for example, say I have a function, get_pg_connection(), which returns a
psycopg2 connection object:

def get_pg_connection(logger_name, database_config):
> logger = logging.getLogger(logger_name)
> try:
> conn = psycopg2.connect(database = database_config['dbname'],
> user = database_config['user'],
> host = database_config['host'],
> port = database_config['port'],
> password = database_config['password'],
> connect_timeout = database_config['timeout'],
> )
> logger.debug('Successfully connected to database
> {host}:{port}/{dbname}'.format(**database_config))
> return conn
> except psycopg2.OperationalError as e:
> logger.error('Error connecting to database
> {0[host]}:{0[port]}/{0[dbname]} - {1}'.format(database_config, e),
> exc_info=True)
> # sys.exit(1) # We should handle this differently? Retry? Move
> onto next one?
> except Exception as e:
> logger.error('Error - {}'.format(e), exc_info=True)

I then call it like so:

conn = get_pg_connection(logger_name, database_config)
> with conn.cursor() as cur:
> cur.execute("""SOME SQL STATEMENT""")
> conn.commit()
> conn.close()

Is the above the correct way of doing things?

So cur.close() will be called when we leave the "with conn_cursor() as cur"
right?

Can I use the conn object that get_pg_connection() returns in a context
handler as well?

with get_pg_connection(logger_name, database_config) as conn:
with conn.cursor() as cur:
cur.execute("""SOME SQL STATEMENT""")
conn.commit()

However, if I'm reading the release notes correctly, the connection *won't*
be closed after we leave the "with get_pg_connection(logger_name,
database_config) as conn" with clause?

So what would be the point of using a context manager for the connection
object as well?

Cheers,
Victor

Responses

Browse psycopg by date

  From Date Subject
Next Message Karsten Hilbert 2013-11-27 11:19:55 Re: Using context managers for connections/cursors - cursors are closed, connections are not?
Previous Message P. Christeas 2013-11-16 08:40:02 Re: Server side prepared statements and executemany