Re: psycopg2: proper positioning of .commit() within try: except: blocks
От | Adrian Klaver |
---|---|
Тема | Re: psycopg2: proper positioning of .commit() within try: except: blocks |
Дата | |
Msg-id | 75723bad-7914-4728-a567-a061e4d3c7d6@aklaver.com обсуждение исходный текст |
Ответ на | Re: psycopg2: proper positioning of .commit() within try: except: blocks (Karsten Hilbert <Karsten.Hilbert@gmx.net>) |
Список | psycopg |
On 9/7/24 14:59, Karsten Hilbert wrote: > 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 ? Yes. > > Karsten > -- > GPG 40BE 5B0E C98E 1713 AFA6 5BC0 3BEA AC80 7D4F C89B -- Adrian Klaver adrian.klaver@aklaver.com
В списке psycopg по дате отправления: