From: | Karsten Hilbert <Karsten(dot)Hilbert(at)gmx(dot)net> |
---|---|
To: | Adrian Klaver <adrian(dot)klaver(at)aklaver(dot)com> |
Cc: | psycopg(at)lists(dot)postgresql(dot)org |
Subject: | Re: psycopg2: proper positioning of .commit() within try: except: blocks |
Date: | 2024-09-07 21:59:41 |
Message-ID: | ZtzMzYTlqN4l5ivN@hermes.hilbert.loc |
Views: | Whole Thread | Raw Message | Download mbox | Resend email |
Thread: | |
Lists: | psycopg |
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
From | Date | Subject | |
---|---|---|---|
Next Message | Adrian Klaver | 2024-09-07 22:09:28 | Re: psycopg2: proper positioning of .commit() within try: except: blocks |
Previous Message | Adrian Klaver | 2024-09-07 21:47:49 | Re: psycopg2: proper positioning of .commit() within try: except: blocks |