Hi,
I'm trying to undersatnd
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