public inbox for [email protected]
help / color / mirror / Atom feedFrom: Karsten Hilbert <[email protected]>
To: Adrian Klaver <[email protected]>
Cc: [email protected]
Subject: Re: psycopg2: proper positioning of .commit() within try: except: blocks
Date: Sat, 7 Sep 2024 23:59:41 +0200
Message-ID: <[email protected]> (raw)
In-Reply-To: <[email protected]>
References: <[email protected]>
<[email protected]>
<[email protected]>
<[email protected]>
<[email protected]>
<[email protected]>
<[email protected]>
<[email protected]>
Am Sat, Sep 07, 2024 at 02:47:49PM -0700 schrieb Adrian Klaver:
> >It is also insufficient because the .commit() itself may
> >elicit exceptions (from the database).
>
> Yeah with Serializable that is part of the package:
No complaints :-)
> > try:
> > do something
> > except:
> > log something
> > try:
> > .commit()
> > except:
> > log something
> >
> >I eventually opted for the last version, except for factoring
> >out the second try: except: block.
>
> I'm not following, if you do that then you won't have a commit.
Perhaps my pseudo-code was to abbreviated.
conn = psycopg2.connection()
curs = conn.cursor()
curs.execute(SQL)
curs.close()
conn.commit()
conn.close()
Written more safely:
conn = psycopg2.connection()
curs = conn.cursor()
try:
curs.execute(SQL)
except SOME_PG_EXCEPTION_VIA_PSYCOPG2:
some_panicstricken_logging()
curs.close()
try:
conn.commit()
except SOME_PG_EXCEPTION_VIA_PSYCOPG2__SUCH_AS_SERIALIZATION_ERROR:
some_more_of_the_panicstricken_logging()
conn.close()
now factored out:
def __commit_me_logging_errors(commit_func):
try:
commit_func()
except SOME_PG_EXCEPTION_VIA_PSYCOPG2__SUCH_AS_SERIALIZATION_ERROR:
some_more_of_the_panicstricken_logging()
return
conn = psycopg2.connection()
curs = conn.cursor()
try:
curs.execute(SQL)
except SOME_PG_EXCEPTION_VIA_PSYCOPG2:
some_panicstricken_logging()
curs.close()
__commit_me_logging_errors(conn.commit)
conn.close()
More clear ?
Karsten
--
GPG 40BE 5B0E C98E 1713 AFA6 5BC0 3BEA AC80 7D4F C89B
view thread (10+ messages) latest in thread
reply
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Reply to all the recipients using the --to and --cc options:
reply via email
To: [email protected]
Cc: [email protected], [email protected], [email protected]
Subject: Re: psycopg2: proper positioning of .commit() within try: except: blocks
In-Reply-To: <[email protected]>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
This inbox is served by agora; see mirroring instructions
for how to clone and mirror all data and code used for this inbox