Rocksolid Light

News from da outaworlds

mail  files  register  groups  login

Message-ID:  

BOFH excuse #392: It's union rules. There's nothing we can do about it. Sorry.


comp / comp.lang.python / Re: psycopg2: proper positioning of .commit() within try: except: blocks

SubjectAuthor
* Re: psycopg2: proper positioning of .commit() within try: except: blocksKarsten Hilbert
`* Re: psycopg2: proper positioning of .commit() within try: except: blocksGreg Ewing
 +- Re: psycopg2 positioning of .commit() (Posting On Python-List Prohibited)Lawrence D'Oliveiro
 +- Re: psycopg2: proper positioning of .commit() within try: except: blocksKarsten Hilbert
 `- Re: psycopg2: proper positioning of .commit() within try: except: blocksKarsten Hilbert

1
Subject: Re: psycopg2: proper positioning of .commit() within try: except: blocks
From: Karsten Hilbert
Newsgroups: comp.lang.python
Date: Sun, 8 Sep 2024 14:13 UTC
References: 1 2 3 4 5 6 7 8 9
Path: eternal-september.org!news.eternal-september.org!feeder3.eternal-september.org!fu-berlin.de!uni-berlin.de!not-for-mail
From: Karsten.Hilbert@gmx.net (Karsten Hilbert)
Newsgroups: comp.lang.python
Subject: Re: psycopg2: proper positioning of .commit() within try: except:
blocks
Date: Sun, 8 Sep 2024 16:13:49 +0200
Lines: 301
Sender: <karsten.hilbert@gmx.net>
Message-ID: <mailman.50.1725804833.2917.python-list@python.org>
References: <Ztx1sZMGTnA3eLP1@hermes.hilbert.loc>
<7cb50df2-9c76-477f-91c9-e149c7637104@aklaver.com>
<ZtytJMhyvtExPxfF@hermes.hilbert.loc>
<5ee80b84-f04b-454d-ab39-45572e0751a1@aklaver.com>
<Zty7ZCMwKQl4C4Id@hermes.hilbert.loc>
<4a1b12fc-24b7-4c7e-b1f2-6ec9c5f341c2@aklaver.com>
<ZtzDubguRDWXwV-t@hermes.hilbert.loc>
<62133ebd-a4a3-471b-9acc-3a988b4fcbd7@btinternet.com>
<Zt2xHedGIh1-dL4g@hermes.hilbert.loc>
Mime-Version: 1.0
Content-Type: text/plain; charset=iso-8859-1
Content-Transfer-Encoding: quoted-printable
X-Trace: news.uni-berlin.de T456cBZlhc3vdD1zp+axhA0/tzn/U3QdOpWjh/7e+/YA==
Cancel-Lock: sha1:Y+NT4xy67pw1Nr/H4wta+51A4wg= sha256:DiZg1R1vac8EZnzqY3L4XGh6wRjplmtrj1JO3MW+Noc=
Return-Path: <karsten.hilbert@gmx.net>
X-Original-To: python-list@python.org
Delivered-To: python-list@mail.python.org
Authentication-Results: mail.python.org; dkim=pass
reason="2048-bit key; unprotected key"
header.d=gmx.net header.i=karsten.hilbert@gmx.net
header.b=jEko3wip; dkim-adsp=pass; dkim-atps=neutral
X-Spam-Status: OK 0.001
X-Spam-Evidence: '*H*': 1.00; '*S*': 0.00; 'def': 0.04; 'despite':
0.05; 'explicitly': 0.07; 'have,': 0.07; 'received:212.227': 0.07;
'sun,': 0.07; 'thing.': 0.07; 'wrong.': 0.07; '"""': 0.09; 'elif':
0.09; 'else:': 0.09; 'finalized': 0.09; 'gpg': 0.09; 'karsten':
0.09; 'schrieb': 0.09; 'skip:_ 20': 0.09; 'something,': 0.09;
'though.': 0.09; 'typically': 0.09; 'log': 0.12; "'':": 0.16;
'(it': 0.16; '1713': 0.16; '2024': 0.16; 'args:': 0.16; 'assert':
0.16; 'be)': 0.16; 'column': 0.16; 'commit': 0.16; 'consolidate':
0.16; 'database.': 0.16; 'dicts': 0.16; 'executed': 0.16;
'failed.': 0.16; 'fetching': 0.16; 'indentation': 0.16; 'lambda':
0.16; 'none)': 0.16; 'none:': 0.16; 'queries.': 0.16;
'received:212.227.15': 0.16; 'skip:_ 60': 0.16; 'subject:() ':
0.16; 'subject:proper': 0.16; 'subject:try': 0.16; 'tuple': 0.16;
'usefully': 0.16; 'problem': 0.16; 'python': 0.16; 'instead':
0.17; 'to:addr:python-list': 0.20; 'exception': 0.22; 'returns':
0.22; 'skip:_ 10': 0.22; 'version': 0.23; 'code': 0.23; 'skip:p
30': 0.23; 'run': 0.23; 'stuff': 0.25; 'cannot': 0.25; 'seems':
0.26; 'pattern': 0.26; "isn't": 0.27; 'bit': 0.27; 'function':
0.27; 'done': 0.28; 'suggest': 0.28; 'whole': 0.30; 'skip:_ 40':
0.31; 'default': 0.31; 'effect': 0.31; 'raise': 0.31; 'false,':
0.32; 'privilege': 0.32; 'returning': 0.32; 'sep': 0.32; 'unless':
0.32; 'but': 0.32; "i'm": 0.33; 'there': 0.33; 'mean': 0.34;
'skip:" 20': 0.34; 'header:In-Reply-To:1': 0.34; 'running': 0.34;
'failed': 0.35; 'close': 0.35; 'thanks,': 0.36; 'source': 0.36;
'missing': 0.37; "skip:' 10": 0.37; "it's": 0.37; 'skip:_ 30':
0.37; 'put': 0.38; 'quite': 0.39; 'single': 0.39; 'list': 0.39;
'block': 0.39; 'level.': 0.40; 'place.': 0.40; 'something': 0.40;
'try': 0.40; 'should': 0.40; 'connection': 0.61; "there's": 0.61;
'skip:i 20': 0.62; 'received:212': 0.62; 'true': 0.63; 'feel':
0.63; 'skip:r 20': 0.64; 'full': 0.64; 'skip:g 30': 0.64;
'transaction': 0.64; 'well': 0.65; 'less': 0.65; 'lead': 0.67;
'skip:t 30': 0.67; 'right': 0.68; 'del': 0.70;
'charset:iso-8859-1': 0.73; 'business': 0.77; '1st': 0.78;
'field': 0.78; '3rd': 0.81; 'queries': 0.81; 'returned': 0.81;
'extra': 0.84; 'eventually': 0.84; 'exceptions': 0.84;
'repetitive': 0.84; 'rob': 0.84; 'subject:within': 0.84;
'transaction.': 0.84; 'true:': 0.84; '"do': 0.91; 'replacing':
0.91; 'retained': 0.91; 'will,': 0.91; 'skip:q 20': 0.95;
'positions': 0.96
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmx.net;
s=s31663417; t=1725804830; x=1726409630; i=karsten.hilbert@gmx.net;
bh=zlVTvCww1ujSZaYXWBd7ICSmhX3L9VWK7ALBG86s+ts=;
h=X-UI-Sender-Class:Date:From:To:Subject:Message-ID:References:
MIME-Version:Content-Type:Content-Transfer-Encoding:In-Reply-To:
cc:content-transfer-encoding:content-type:date:from:message-id:
mime-version:reply-to:subject:to;
b=jEko3wipdJtt/6dgrDKejOpI8ZBHYGKRYbIMpCw3F3Tvl5TJ9nADyVb94LbIFxwR
yKxUlErBGsp0ufxqqRD5PSvaHk7NKvfQJCqs9r+14+j20RIfY6tIb6o4byL9Ou0RF
9iH94fotXmEfIEhLwpKHhKC4Cnu3x9w7ff570k35a8rJjP2kX1bANUu72pxgTWENA
X4AcThdDXYBfxJIKAlJ+ulcVoizZ32Sm4dDSSjKbSnJZN1IxELdd0eOIwyPW22n+C
1LZYutmIl5LgMPRtDRPmJaPOV2H9EsJd4VSLlF+XZmtZ0CMuuxH+2RQ/X97578OcS
hSGSt0ugR85x7QOLrQ==
X-UI-Sender-Class: 724b4f7f-cbec-4199-ad4e-598c01a50d3a
Content-Disposition: inline
In-Reply-To: <62133ebd-a4a3-471b-9acc-3a988b4fcbd7@btinternet.com>
Ma_X_il-Followup-to: d
Re_X_turn-receipt-to: Karsten.Hilbert@gmx.net
Di_X_sposition-Notification-To: Karsten.Hilbert@gmx.net
X-Confi_X_rm-Reading-To: Karsten.Hilbert@gmx.net
X-Pri_X_ority: 2 (High)
X-Provags-ID: V03:K1:ux0uNH2lgMJzfEAVAvzw0wURuYq2qhHQoM8dYJIA2OwtbJkSepq
2z3DJ7Dj1LxMxa20UHIGo8t4Cn1LyV1f++/YpTFL+7uNQMgI5u6IxMkBcupZYmOjSiZoYz5
CiE4n7abO/L++c7BngoUaT0yN0LQTwdC04hkjrDWlEhQWlgsFJePimpT/2SPscekCunbAxW
6qL8c9/hmMYD4+M0cBlmw==
X-Spam-Flag: NO
UI-OutboundReport: notjunk:1;M01:P0:icBKUh5YZis=;JFqsNok+bj3fwpso/zZcQp9XsCf
ddFNoMEKQPiLxKvypNtUFNrZ/zH0iwLQyRI6Vr4DUoOyKaNqAePTyFb8RPOY3Hv/58iCZPK/q
oGqjVGGWPZyJc74FxG9Y+12OnWqKtF9NzZXTyt8bGPOMJdUgAdHqvoDns9fjSKcqT171JcZeP
G8fM+vJYBbOtE8el+FLvgoJFdmTWqUa5AALlBCIqs0Qp05ezWiSCcnKysSnoPkeWkATyU0k/p
bA2GcOqjBxLUkSGBXBaMjN6ePcd7W3c/ZOod4Su3sL0Alc+DyD88xgkO3mbG1LyAlMLubL2hc
HtJMCpZmkKRlIr35OGpmx55n7I/wlWWiPh0MOaMPg0rUVdratYCg0FjslYoo73vu/11gMewIL
wYsMlfMdiC7UFW4opw9pi2fjf2CPWVcvNXD0jMywDnzjpXSukV1F4IWvwB7Efmze+1WjkGHWz
+ME5gKsczROHskoBsDxV1nMU7S58T0hsbvsXMSMWqgbr6R7hCoiNQsMwLRwGrjrSwTxPoLddX
b1SIIUHThqNjauu0iWHNkYVIsQn50dN7v10rdlEN53RizergFXyUSOfcuO2sF30jONL5yRoEW
dSnRvIFTnY55i7KSQQu3j5yflI0iJ9g9Jc9Lh0tUXpX6Z2mto96PiIkljm1QvW+z1Lye7tm+/
e93vcM2Cg0Z7s9iwJnAy/7OP/Fq7fWDHye0LdOErHCHrH0rg8W3GFdhOPnSEZecnmnw0AvQzJ
96GRmrDrjhQ1R1PUidQgMmbKRhVlUMP1POQLNJsOeXHA32CqwacrSJP1fe2/Xj0grZ6QeZHAg
1eRW3wegEtm5S2F6e1wdgTaw==
X-BeenThere: python-list@python.org
X-Mailman-Version: 2.1.39
Precedence: list
List-Id: General discussion list for the Python programming language
<python-list.python.org>
List-Unsubscribe: <https://mail.python.org/mailman/options/python-list>,
<mailto:python-list-request@python.org?subject=unsubscribe>
List-Archive: <https://mail.python.org/pipermail/python-list/>
List-Post: <mailto:python-list@python.org>
List-Help: <mailto:python-list-request@python.org?subject=help>
List-Subscribe: <https://mail.python.org/mailman/listinfo/python-list>,
<mailto:python-list-request@python.org?subject=subscribe>
X-Mailman-Original-Message-ID: <Zt2xHedGIh1-dL4g@hermes.hilbert.loc>
X-Mailman-Original-References: <Ztx1sZMGTnA3eLP1@hermes.hilbert.loc>
<7cb50df2-9c76-477f-91c9-e149c7637104@aklaver.com>
<ZtytJMhyvtExPxfF@hermes.hilbert.loc>
<5ee80b84-f04b-454d-ab39-45572e0751a1@aklaver.com>
<Zty7ZCMwKQl4C4Id@hermes.hilbert.loc>
<4a1b12fc-24b7-4c7e-b1f2-6ec9c5f341c2@aklaver.com>
<ZtzDubguRDWXwV-t@hermes.hilbert.loc>
<62133ebd-a4a3-471b-9acc-3a988b4fcbd7@btinternet.com>
View all headers

Am Sun, Sep 08, 2024 at 02:58:03PM +0100 schrieb Rob Cliffe via Python-list:

> >Ugly:
> >
> > try:
> > do something
> > except:
> > log something
> > finally:
> > try:
> > .commit()
> > except:
> > log some more
> >
> >Fair but not feeling quite safe:
> >
> > try:
> > do something
> > .commit()
> > except:
> > log something
> >
> >Boring and repetitive and safe(r):
> >
> > 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.

> Unless I'm missing something, the 1st & 3rd versions always do the commit() even after
> the first bit fails, which seems wrong.

Well, it does run a Python function called "commit". That
function will call "COMMIT" on the database. The end result
will be correct (at the SQL level) because the COMMIT will
not effect a durable commit of data when the SQL in "do
something" had failed.

We have, however, elicited that there may well be other
things belonging into the running business level transaction
which may fail and which should lead to data not being
committed despite being technically correct at the SQL level.

> I suggest the 1st version but replacing "finally" by "else".  Then the try-commit-except
> will not be executed if the "something" fails.

The whole point was to consolidate the commit into one place.
It is unfortunately named, though. It should be called
"close_transaction".

> Perhaps the extra indentation of the second try block is a bit ugly, but it is more
> important that it does the right thing.
> If it is convenient (it may not be) to put the whole thing in a function, you may feel
> that the follwing is less ugly:

The whole thing does reside inside a function but the exit-early pattern

> try:
> do something
> except:
> log something
> return
> try:
> .commit()
> except:
> log some more
> return

won't help as there's more stuff to be done inside that function.

Thanks,
Karsten

For what it's worth here's the current state of code:

#------------------------------------------------------------------------
def __safely_close_cursor_and_rollback_close_conn(close_cursor=None, rollback_tx=None, close_conn=None):
if close_cursor:
try:
close_cursor()
except PG_ERROR_EXCEPTION as pg_exc:
_log.exception('cannot close cursor')
gmConnectionPool.log_pg_exception_details(pg_exc)
if rollback_tx:
try:
# need to rollback so ABORT state isn't retained in pooled connections
rollback_tx()
except PG_ERROR_EXCEPTION as pg_exc:
_log.exception('cannot rollback transaction')
gmConnectionPool.log_pg_exception_details(pg_exc)
if close_conn:
try:
close_conn()
except PG_ERROR_EXCEPTION as pg_exc:
_log.exception('cannot close connection')
gmConnectionPool.log_pg_exception_details(pg_exc)

#------------------------------------------------------------------------
def __log_notices(notices_accessor=None):
for notice in notices_accessor.notices:
_log.debug(notice.replace('\n', '/').replace('\n', '/'))
del notices_accessor.notices[:]

#------------------------------------------------------------------------
def __perhaps_reraise_as_permissions_error(pg_exc, curs):
if pg_exc.pgcode != PG_error_codes.INSUFFICIENT_PRIVILEGE:
return

# privilege problem -- normalize as GNUmed exception
details = 'Query: [%s]' % curs.query.decode(errors = 'replace').strip().strip('\n').strip().strip('\n')
if curs.statusmessage != '':
details = 'Status: %s\n%s' % (
curs.statusmessage.strip().strip('\n').strip().strip('\n'),
details
)
if pg_exc.pgerror is None:
msg = '[%s]' % pg_exc.pgcode
else:
msg = '[%s]: %s' % (pg_exc.pgcode, pg_exc.pgerror)
raise gmExceptions.AccessDenied (
msg,
source = 'PostgreSQL',
code = pg_exc.pgcode,
details = details
)

#------------------------------------------------------------------------
def run_rw_queries (
link_obj:_TLnkObj=None,
queries:_TQueries=None,
end_tx:bool=False,
return_data:bool=None,
get_col_idx:bool=False,
verbose:bool=False
) -> tuple[list[dbapi.extras.DictRow], dict[str, int] | None]:
"""Convenience function for running read-write queries.

Typically (part of) a transaction.

Args:
link_obj: None, cursor, connection
queries:

* a list of dicts [{'cmd': <string>, 'args': <dict> or <tuple>)
* to be executed as a single transaction
* the last query may usefully return rows, such as:

SELECT currval('some_sequence');
or
INSERT/UPDATE ... RETURNING some_value;

end_tx:

* controls whether the transaction is finalized (eg.
COMMITted/ROLLed BACK) or not, this allows the
call to run_rw_queries() to be part of a framing
transaction
* if link_obj is a *connection* then "end_tx" will
default to False unless it is explicitly set to
True which is taken to mean "yes, you do have full
control over the transaction" in which case the
transaction is properly finalized
* if link_obj is a *cursor* we CANNOT finalize the
transaction because we would need the connection for that
* if link_obj is *None* "end_tx" will, of course, always
be True, because we always have full control over the
connection, not ending the transaction would be pointless

return_data:

* if true, the returned data will include the rows
the last query selected
* if false, it returns None instead

get_col_idx:

* True: the returned tuple will include a dictionary
mapping field names to column positions
* False: the returned tuple includes None instead of a field mapping dictionary

Returns:

* (None, None) if last query did not return rows
* ("fetchall() result", <index>) if last query returned any rows and "return_data" was True

* for *index* see "get_col_idx"
"""
assert queries is not None, '<queries> must not be None'
assert isinstance(link_obj, (dbapi._psycopg.connection, dbapi._psycopg.cursor, type(None))), '<link_obj> must be None, a cursor, or a connection, but [%s] is of type (%s)' % (link_obj, type(link_obj))

if link_obj is None:
conn = get_connection(readonly = False)
curs = conn.cursor()
conn_close = conn.close
tx_commit = conn.commit
tx_rollback = conn.rollback
curs_close = curs.close
notices_accessor = conn
else:
conn_close = lambda *x: None
tx_commit = lambda *x: None
tx_rollback = lambda *x: None
curs_close = lambda *x: None
if isinstance(link_obj, dbapi._psycopg.cursor):
curs = link_obj
notices_accessor = curs.connection
elif isinstance(link_obj, dbapi._psycopg.connection):
curs = link_obj.cursor()
curs_close = curs.close
notices_accessor = link_obj
if end_tx:
tx_commit = link_obj.commit
tx_rollback = link_obj.rollback
for query in queries:
try:
args = query['args']
except KeyError:
args = None
try:
curs.execute(query['cmd'], args)
if verbose:
gmConnectionPool.log_cursor_state(curs)
__log_notices(notices_accessor)
# DB related exceptions
except dbapi.Error as pg_exc:
_log.error('query failed in RW connection')
gmConnectionPool.log_pg_exception_details(pg_exc)
__log_notices(notices_accessor)
__safely_close_cursor_and_rollback_close_conn (
curs_close,
tx_rollback,
conn_close
)
__perhaps_reraise_as_permissions_error(pg_exc, curs)
# not a permissions problem
gmLog2.log_stack_trace()
raise

# other exceptions
except Exception:
_log.exception('error running query in RW connection')
gmConnectionPool.log_cursor_state(curs)
__log_notices(notices_accessor)
gmLog2.log_stack_trace()
__safely_close_cursor_and_rollback_close_conn (
curs_close,
tx_rollback,
conn_close
)
raise

if not return_data:
curs_close()
tx_commit()
conn_close()
return (None, None)

data = None
try:
data = curs.fetchall()
except Exception:
_log.exception('error fetching data from RW query')
gmLog2.log_stack_trace()
__safely_close_cursor_and_rollback_close_conn (
curs_close,
tx_rollback,
conn_close
)
raise


Click here to read the complete article
Subject: Re: psycopg2: proper positioning of .commit() within try: except: blocks
From: Greg Ewing
Newsgroups: comp.lang.python
Date: Mon, 9 Sep 2024 01:48 UTC
References: 1 2 3 4 5 6 7 8 9 10
Path: eternal-september.org!news.eternal-september.org!feeder3.eternal-september.org!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail
From: greg.ewing@canterbury.ac.nz (Greg Ewing)
Newsgroups: comp.lang.python
Subject: Re: psycopg2: proper positioning of .commit() within try: except:
blocks
Date: Mon, 9 Sep 2024 13:48:32 +1200
Lines: 11
Message-ID: <lk72fhFo32jU1@mid.individual.net>
References: <Ztx1sZMGTnA3eLP1@hermes.hilbert.loc>
<7cb50df2-9c76-477f-91c9-e149c7637104@aklaver.com>
<ZtytJMhyvtExPxfF@hermes.hilbert.loc>
<5ee80b84-f04b-454d-ab39-45572e0751a1@aklaver.com>
<Zty7ZCMwKQl4C4Id@hermes.hilbert.loc>
<4a1b12fc-24b7-4c7e-b1f2-6ec9c5f341c2@aklaver.com>
<ZtzDubguRDWXwV-t@hermes.hilbert.loc>
<62133ebd-a4a3-471b-9acc-3a988b4fcbd7@btinternet.com>
<Zt2xHedGIh1-dL4g@hermes.hilbert.loc>
<mailman.50.1725804833.2917.python-list@python.org>
Mime-Version: 1.0
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 7bit
X-Trace: individual.net awOybTY9hYtMiE1VV+7faQyv7odWjHKl+3UHoQO8KkMFOXufmE
Cancel-Lock: sha1:ocr2XKjZYb98DQO4i7tGZYmuHqY= sha256:xZCV6/uk/tUcbWnf9B89Dz3xw6X9T+H/XYSyUR0Lxa0=
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:91.0)
Gecko/20100101 Thunderbird/91.3.2
Content-Language: en-US
In-Reply-To: <mailman.50.1725804833.2917.python-list@python.org>
View all headers

On 9/09/24 2:13 am, Karsten Hilbert wrote:
> For what it's worth here's the current state of code:

That code doesn't inspire much confidence in me. It's far too
convoluted with too much micro-management of exceptions.

I would much prefer to have just *one* place where exceptions are
caught and logged.

--
Greg

Subject: Re: psycopg2 positioning of .commit() (Posting On Python-List Prohibited)
From: Lawrence D'Oliv
Newsgroups: comp.lang.python
Organization: A noiseless patient Spider
Date: Mon, 9 Sep 2024 03:34 UTC
References: 1 2 3 4 5 6 7 8 9 10 11
Path: eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail
From: ldo@nz.invalid (Lawrence D'Oliveiro)
Newsgroups: comp.lang.python
Subject: Re: psycopg2 positioning of .commit() (Posting On Python-List
Prohibited)
Date: Mon, 9 Sep 2024 03:34:27 -0000 (UTC)
Organization: A noiseless patient Spider
Lines: 11
Message-ID: <vblqc3$2987j$1@dont-email.me>
References: <Ztx1sZMGTnA3eLP1@hermes.hilbert.loc>
<7cb50df2-9c76-477f-91c9-e149c7637104@aklaver.com>
<ZtytJMhyvtExPxfF@hermes.hilbert.loc>
<5ee80b84-f04b-454d-ab39-45572e0751a1@aklaver.com>
<Zty7ZCMwKQl4C4Id@hermes.hilbert.loc>
<4a1b12fc-24b7-4c7e-b1f2-6ec9c5f341c2@aklaver.com>
<ZtzDubguRDWXwV-t@hermes.hilbert.loc>
<62133ebd-a4a3-471b-9acc-3a988b4fcbd7@btinternet.com>
<Zt2xHedGIh1-dL4g@hermes.hilbert.loc>
<mailman.50.1725804833.2917.python-list@python.org>
<lk72fhFo32jU1@mid.individual.net>
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Injection-Date: Mon, 09 Sep 2024 05:34:27 +0200 (CEST)
Injection-Info: dont-email.me; posting-host="48619980776be9ad3edbc43d1fdbfd55";
logging-data="2400499"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX19M5VfxF005bQQxNDQ+kp/w"
User-Agent: Pan/0.160 (Toresk; )
Cancel-Lock: sha1:fGG0MkgE4jO5yWVK3ZxZ6F2cnR8=
View all headers

On Mon, 9 Sep 2024 13:48:32 +1200, Greg Ewing wrote:

> I would much prefer to have just *one* place where exceptions are caught
> and logged.

Why catch exceptions at all? The only kind of database-related exception
I’ve felt the need to catch so far is the occasional IntegrityError from
trying to insert a record with a duplicate key (and that only in certain
situations). Anything else (particularly SQL syntax errors) I would rather
just leave to the default exception-handling mechanism -- why waste time
reinventing its information-reporting abilities?

Subject: Re: psycopg2: proper positioning of .commit() within try: except: blocks
From: Karsten Hilbert
Newsgroups: comp.lang.python
Date: Mon, 9 Sep 2024 08:40 UTC
References: 1 2 3 4 5 6 7 8 9 10 11
Path: eternal-september.org!news.eternal-september.org!feeder3.eternal-september.org!fu-berlin.de!uni-berlin.de!not-for-mail
From: Karsten.Hilbert@gmx.net (Karsten Hilbert)
Newsgroups: comp.lang.python
Subject: Re: psycopg2: proper positioning of .commit() within try: except:
blocks
Date: Mon, 9 Sep 2024 10:40:14 +0200
Lines: 14
Sender: <karsten.hilbert@gmx.net>
Message-ID: <mailman.0.1725871219.31645.python-list@python.org>
References: <7cb50df2-9c76-477f-91c9-e149c7637104@aklaver.com>
<ZtytJMhyvtExPxfF@hermes.hilbert.loc>
<5ee80b84-f04b-454d-ab39-45572e0751a1@aklaver.com>
<Zty7ZCMwKQl4C4Id@hermes.hilbert.loc>
<4a1b12fc-24b7-4c7e-b1f2-6ec9c5f341c2@aklaver.com>
<ZtzDubguRDWXwV-t@hermes.hilbert.loc>
<62133ebd-a4a3-471b-9acc-3a988b4fcbd7@btinternet.com>
<Zt2xHedGIh1-dL4g@hermes.hilbert.loc>
<mailman.50.1725804833.2917.python-list@python.org>
<lk72fhFo32jU1@mid.individual.net>
<Zt60bl8MTt_5Cj93@hermes.hilbert.loc>
Mime-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: quoted-printable
X-Trace: news.uni-berlin.de R90q1BvBrx8QJ9mp514TXApY41Sy/YMGTdn9Z9LCGglQ==
Cancel-Lock: sha1:qAQV2HINbwsbFyoS6hUlrj38r44= sha256:eb0ztoAsPC6XhS7aqBvMb38cOrH2uuhDeNJt2ftWWGc=
Return-Path: <karsten.hilbert@gmx.net>
X-Original-To: python-list@python.org
Delivered-To: python-list@mail.python.org
Authentication-Results: mail.python.org; dkim=pass
reason="2048-bit key; unprotected key"
header.d=gmx.net header.i=karsten.hilbert@gmx.net
header.b=rczBGXYo; dkim-adsp=pass; dkim-atps=neutral
X-Spam-Status: OK 0.020
X-Spam-Evidence: '*H*': 0.96; '*S*': 0.00; 'received:212.227': 0.07;
'gpg': 0.09; 'karsten': 0.09; 'schrieb': 0.09; '1713': 0.16;
'2024': 0.16; 'greg': 0.16; 'received:212.227.15': 0.16;
'subject:() ': 0.16; 'subject:proper': 0.16; 'subject:try': 0.16;
'to:addr:python-list': 0.20; 'code': 0.23; "doesn't": 0.32; 'sep':
0.32; 'header:In-Reply-To:1': 0.34; 'mon,': 0.36; "it's": 0.37;
'me.': 0.62; 'received:212': 0.62; 'caught': 0.67; 'confidence':
0.76; 'exceptions': 0.84; 'subject:within': 0.84
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmx.net;
s=s31663417; t=1725871214; x=1726476014; i=karsten.hilbert@gmx.net;
bh=hPR+S36MKlLPeIEl3jZKujMQ+5kMOtc8+BO0TpPipos=;
h=X-UI-Sender-Class:Date:From:To:Subject:Message-ID:References:
MIME-Version:Content-Type:In-Reply-To:Content-Transfer-Encoding:
cc:content-transfer-encoding:content-type:date:from:message-id:
mime-version:reply-to:subject:to;
b=rczBGXYoZtHn340+1oRneEVfbxMREvX1p0jAOXEkgY18VAFDgh0GxHQy9sQDWbei
DUTbsdL11ISRp+hltfPv0HagY3a1KNTfaiVIJfo/E6AnNM+arg4yhj/klyHQTV84l
yRw8Zg6MZ+sM6ZXFpPtJwtMZ1whHGlOl25hyaQ8AdLnxs4CDz1RCAwxtLzcyY2HHM
o6nsEs1x+9v0Z+fkrBCax5xanvHPm7UJ+vG9tiwwRJ19OS2drJ2+QvaEs94iPqS28
HCWtGKp6qT6Ss35SwNh7XgluowkLhMB1QXLrszs6Y9M0zw2csaef+0sNGXgHjY0ls
SU0hgTRqBR8RyT/IiA==
X-UI-Sender-Class: 724b4f7f-cbec-4199-ad4e-598c01a50d3a
Content-Disposition: inline
In-Reply-To: <lk72fhFo32jU1@mid.individual.net>
Ma_X_il-Followup-to: d
Re_X_turn-receipt-to: Karsten.Hilbert@gmx.net
Di_X_sposition-Notification-To: Karsten.Hilbert@gmx.net
X-Confi_X_rm-Reading-To: Karsten.Hilbert@gmx.net
X-Pri_X_ority: 2 (High)
X-Provags-ID: V03:K1:fc8Efw3v1JlRmiMx9mDJ8FTGp4w2MIbBpQzgQwfj0Puho8ZKTdy
3+C6LD1pEfSax3+7fjip/7x2b1rEvpD2GW8LQxJDxQFJcY9d5JS2bEej3dGYE+BOEV97Fx0
av2HWTS2VouqfR5GGpWIW90CKGg86SxISjqtNLLy1sRZ1k9EMAabAAPj2OpohQxT68zKP7O
/Sm0JhQX5TLS5+kJPvRUA==
X-Spam-Flag: NO
UI-OutboundReport: notjunk:1;M01:P0:XbS+48/2tqs=;dxznGOW+eaeuNvT+MNlnwdhdQGc
G/Ibgf/k/cX6CcN23wf/bmQBqrfTiahbjRVxSA4k+6pS3naQzO7l3sJX1Z4Z21XdijwSyNtoB
vd6KfHkx2SFotzU29iRPOgKvZgf44TRiogI/3cVSrNQmgUDG08o9tH/eGgEUUmfF7o+RNcmoX
c3s9U5Ii6i6/cNncfSsmc+x4o2V+YYGO2Tdorgu8XGRXgVGMpImr82S9jZCt74VlbmfpyV+DP
0wEVzdJxQ7rzEQOS5TILdEcCA15eNUwCCrxmOf+cz2OnPt9pSNdZu/RQRimegGrWj8lf3ar5R
lcBdTtqw1OzrpeTAfxeTxioXW42dW8q5MWUdsoZLIg/KROsQgWFkEuIM1AfWlyAD2BJkpyr3O
tsg8YCdvtWkfcIdOEvJfO2V4QNYf8dBHbEcGdsI53Evc+Qg070P3xK5t36SoZ9Cvfiuc0nhBF
q7FrR7Tk2WhR7akvtoIKeEp7ThCaVFJ1SraB4gIznwjefVHWee4r2rKdNozl2ZezYjZJqi6h4
U1DisTs9TWASm18sNGcsGBzXXp9tMFofdIQU6R+v1VuAKGT63YSSt8V4ZikQIjHT/7RATr0Ft
r1nTvrFpXamjz4qqXG1NK0PtJNdXySbbE3wqXILUSEcEpub38vZrYC9ddQflqmkSlXpUZBXtf
rZ4uEIBeW8Nwd74nvf6n8iNGbO5MKq7+4FIs1UTXN/v8qDTS43OdpYo15mpw3SnB/n2Tln+6Y
iBNUokVPJIUV3maZ+BG9KxxqmJwxzUcQA3EyjHIWMRWbm2m532p82A5k7/iQxjP3F5BbgIb6/
nYEjW12u1CmnDW6uOfkaBnCw==
X-BeenThere: python-list@python.org
X-Mailman-Version: 2.1.39
Precedence: list
List-Id: General discussion list for the Python programming language
<python-list.python.org>
List-Unsubscribe: <https://mail.python.org/mailman/options/python-list>,
<mailto:python-list-request@python.org?subject=unsubscribe>
List-Archive: <https://mail.python.org/pipermail/python-list/>
List-Post: <mailto:python-list@python.org>
List-Help: <mailto:python-list-request@python.org?subject=help>
List-Subscribe: <https://mail.python.org/mailman/listinfo/python-list>,
<mailto:python-list-request@python.org?subject=subscribe>
X-Mailman-Original-Message-ID: <Zt60bl8MTt_5Cj93@hermes.hilbert.loc>
X-Mailman-Original-References: <7cb50df2-9c76-477f-91c9-e149c7637104@aklaver.com>
<ZtytJMhyvtExPxfF@hermes.hilbert.loc>
<5ee80b84-f04b-454d-ab39-45572e0751a1@aklaver.com>
<Zty7ZCMwKQl4C4Id@hermes.hilbert.loc>
<4a1b12fc-24b7-4c7e-b1f2-6ec9c5f341c2@aklaver.com>
<ZtzDubguRDWXwV-t@hermes.hilbert.loc>
<62133ebd-a4a3-471b-9acc-3a988b4fcbd7@btinternet.com>
<Zt2xHedGIh1-dL4g@hermes.hilbert.loc>
<mailman.50.1725804833.2917.python-list@python.org>
<lk72fhFo32jU1@mid.individual.net>
View all headers

Am Mon, Sep 09, 2024 at 01:48:32PM +1200 schrieb Greg Ewing via Python-list:

> That code doesn't inspire much confidence in me. It's far too
> convoluted with too much micro-management of exceptions.
>
> I would much prefer to have just *one* place where exceptions are
> caught and logged.

I am open to suggestions.

Karsten
--
GPG 40BE 5B0E C98E 1713 AFA6 5BC0 3BEA AC80 7D4F C89B

Subject: Re: psycopg2: proper positioning of .commit() within try: except: blocks
From: Karsten Hilbert
Newsgroups: comp.lang.python
Date: Mon, 9 Sep 2024 08:56 UTC
References: 1 2 3 4 5 6 7 8 9 10 11
Path: eternal-september.org!news.eternal-september.org!feeder3.eternal-september.org!fu-berlin.de!uni-berlin.de!not-for-mail
From: Karsten.Hilbert@gmx.net (Karsten Hilbert)
Newsgroups: comp.lang.python
Subject: Re: psycopg2: proper positioning of .commit() within try: except:
blocks
Date: Mon, 9 Sep 2024 10:56:47 +0200
Lines: 20
Sender: <karsten.hilbert@gmx.net>
Message-ID: <mailman.1.1725872210.31645.python-list@python.org>
References: <7cb50df2-9c76-477f-91c9-e149c7637104@aklaver.com>
<ZtytJMhyvtExPxfF@hermes.hilbert.loc>
<5ee80b84-f04b-454d-ab39-45572e0751a1@aklaver.com>
<Zty7ZCMwKQl4C4Id@hermes.hilbert.loc>
<4a1b12fc-24b7-4c7e-b1f2-6ec9c5f341c2@aklaver.com>
<ZtzDubguRDWXwV-t@hermes.hilbert.loc>
<62133ebd-a4a3-471b-9acc-3a988b4fcbd7@btinternet.com>
<Zt2xHedGIh1-dL4g@hermes.hilbert.loc>
<mailman.50.1725804833.2917.python-list@python.org>
<lk72fhFo32jU1@mid.individual.net>
<Zt64T0-nsBN5UhBR@hermes.hilbert.loc>
Mime-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: quoted-printable
X-Trace: news.uni-berlin.de mFg5+wZEYkuVj6PsaZ3c5AdkLyBi/NaeaHC381FvgXZg==
Cancel-Lock: sha1:bnpqE4lNQwE7GE+dEf1KjGMlQIs= sha256:xmvh2ehHXgjr/hAhMhG1oiwWXW7sYVtEpeuj6AV8wVw=
Return-Path: <karsten.hilbert@gmx.net>
X-Original-To: python-list@python.org
Delivered-To: python-list@mail.python.org
Authentication-Results: mail.python.org; dkim=pass
reason="2048-bit key; unprotected key"
header.d=gmx.net header.i=karsten.hilbert@gmx.net
header.b=SSIG8PuM; dkim-adsp=pass; dkim-atps=neutral
X-Spam-Status: OK 0.040
X-Spam-Evidence: '*H*': 0.92; '*S*': 0.00; 'received:212.227': 0.07;
'gpg': 0.09; 'karsten': 0.09; 'schrieb': 0.09; '1713': 0.16;
'2024': 0.16; 'exception.': 0.16; 'greg': 0.16; 'logs': 0.16;
'received:212.227.15': 0.16; 'subject:() ': 0.16;
'subject:proper': 0.16; 'subject:try': 0.16; 'larger': 0.17;
'to:addr:python-list': 0.20; 'code': 0.23; "doesn't": 0.32; 'sep':
0.32; 'header:In-Reply-To:1': 0.34; 'mon,': 0.36; "it's": 0.37;
'two': 0.39; 'skip:u 20': 0.39; 'both': 0.40; 'me.': 0.62;
'received:212': 0.62; 'top': 0.65; 'caught': 0.67; 'them,': 0.70;
'confidence': 0.76; 'catching': 0.84; 'exceptions': 0.84;
'subject:within': 0.84; 'differently': 0.91
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmx.net;
s=s31663417; t=1725872207; x=1726477007; i=karsten.hilbert@gmx.net;
bh=6+1RLm0Xe5p0hoFw2QnjuHUsgQTqTsMjIWt5zGWt3+0=;
h=X-UI-Sender-Class:Date:From:To:Subject:Message-ID:References:
MIME-Version:Content-Type:In-Reply-To:Content-Transfer-Encoding:
cc:content-transfer-encoding:content-type:date:from:message-id:
mime-version:reply-to:subject:to;
b=SSIG8PuMC0cmsYWFS+W7PB2JHrJ4idsZfn6REqDWixyaNUsaRRMVULz6YEn1v7ub
IOuMm6ODQ1CwYeLX03W/LJ6POJohziZB37Q/905Wib0lX5L8w8B71Xi26ICLeEhwV
EU9RqikRhOVkLVd4HxqHpu7WHTzIx1dh0kgxiUP8RZK5kVWI4rG613vx0wM9TghTn
Dq95cNJIA9HZJd3d0rBgayfnHxIfGHVj3NYjNoy3aIl1KOMkzvL74KomV9cxvOuk3
JusCrhavYOXRGleOKI3/2a5fu/+EDSmErF7xW+ge86uYjNp6whQrH8uT/PKFHoIXY
CZzzpHvDo+q+6/T7DA==
X-UI-Sender-Class: 724b4f7f-cbec-4199-ad4e-598c01a50d3a
Content-Disposition: inline
In-Reply-To: <lk72fhFo32jU1@mid.individual.net>
Ma_X_il-Followup-to: d
Re_X_turn-receipt-to: Karsten.Hilbert@gmx.net
Di_X_sposition-Notification-To: Karsten.Hilbert@gmx.net
X-Confi_X_rm-Reading-To: Karsten.Hilbert@gmx.net
X-Pri_X_ority: 2 (High)
X-Provags-ID: V03:K1:niU7Wm7AQDU9dEWbxpGmHdwThuVuAQJbD3V1EqoPKs0mQ3PiImd
4Bbpsojz49MjvMjkZxy1Hy75bWSeQAJKirH+i6kfmFN4LoSre3tUJxv2+LJS3s8f2vfoXEL
4lPRAzd53B1p3wE4zoV49ttBWZR4VSU881l2C0bXs1O2xI9X3xzipD6cLQyUwOLd5k5KNE9
80gWRg/yz020if+7xs5Ww==
X-Spam-Flag: NO
UI-OutboundReport: notjunk:1;M01:P0:Xrjc0qaix/o=;/abE06uqZh8fRaRfhFGv0GI/hMr
41RBTyLDH9LR/B5YZiQ51SRG82s0IvEYrGpYwb2id64Ofnk0PuxaTqTSY8zVmxFJ5Bllk5w5n
hmb2PuFSyLweYebEnFFYI2Ps+14j7wyzkXS86FllKqboOFvjJLvdO5Z18XcpdftREBVclfuor
fM5pF8+Q78CwexQ078Hnp4hsZ0QiNG+CtbUqLUkZj1nGgVV/tv2M58SQ2yfTu/xg+b3MA+vt5
K27gROfjwmSjYurGooF+Id4Yh+u1FL0yIsCIKwN1/FDFKP24gERTXakcTfJd5BHa76V97FOto
3NqTUQqAvgHa26SUrNN3bG4boS/OZcJB5MKLQ4cj2Kw6TsJ1IDy7a5lMlkfsiMy7sS7GaOdCZ
Qw+YtDl05nDaRA9cWyvVP8Qi5XGBzw+8LIuoycog5KSlUN5UdT9K9I7t/p/HWfYCvsUo2E657
1EMqg04njn4kdHUYsoNbsqIXNkdKV8TyA/Teqf2RMwIzw2+ztXou3OqRKxDxWJiJyUW41IqLy
6K/yrTQ+Hy5ldJ1EfiNlweS7hybNFkhqyQmIUIBzXGeyqqBv976GrrS9SQVXcGwg3Q+6ogFGs
zYft6qI4DEYp8VrgJGgF81P6JDFmt+xHml3OsBJfps6GDQIArtc+EGLraxpGSNQUUIyVQxXph
g46evDGyikZgfQfuOMQFTsTd4fP78D3l7TQ5CZMXvsZkubOM0cetrnijKPpJL03RVwNsri1gC
rwkkuu65RbhihyYY1ibaTCjSzwVEuvtGFoyr5QVNi7F9yDvJyLsz/qmXN24FT0t142WSCbZtU
Fh1JkAnVYBGSFPzo/Rwzd+IQ==
X-BeenThere: python-list@python.org
X-Mailman-Version: 2.1.39
Precedence: list
List-Id: General discussion list for the Python programming language
<python-list.python.org>
List-Unsubscribe: <https://mail.python.org/mailman/options/python-list>,
<mailto:python-list-request@python.org?subject=unsubscribe>
List-Archive: <https://mail.python.org/pipermail/python-list/>
List-Post: <mailto:python-list@python.org>
List-Help: <mailto:python-list-request@python.org?subject=help>
List-Subscribe: <https://mail.python.org/mailman/listinfo/python-list>,
<mailto:python-list-request@python.org?subject=subscribe>
X-Mailman-Original-Message-ID: <Zt64T0-nsBN5UhBR@hermes.hilbert.loc>
X-Mailman-Original-References: <7cb50df2-9c76-477f-91c9-e149c7637104@aklaver.com>
<ZtytJMhyvtExPxfF@hermes.hilbert.loc>
<5ee80b84-f04b-454d-ab39-45572e0751a1@aklaver.com>
<Zty7ZCMwKQl4C4Id@hermes.hilbert.loc>
<4a1b12fc-24b7-4c7e-b1f2-6ec9c5f341c2@aklaver.com>
<ZtzDubguRDWXwV-t@hermes.hilbert.loc>
<62133ebd-a4a3-471b-9acc-3a988b4fcbd7@btinternet.com>
<Zt2xHedGIh1-dL4g@hermes.hilbert.loc>
<mailman.50.1725804833.2917.python-list@python.org>
<lk72fhFo32jU1@mid.individual.net>
View all headers

Am Mon, Sep 09, 2024 at 01:48:32PM +1200 schrieb Greg Ewing via Python-list:

> That code doesn't inspire much confidence in me. It's far too
> convoluted with too much micro-management of exceptions.

It is catching two exceptions, re-raising both of them,
except for re-raising one of them as another kind of
exception. What would you doing differently and how ?

> I would much prefer to have just *one* place where exceptions are
> caught and logged.

There's, of course, a top level handler which logs and
user-displays-as-appropriate any exceptions. This is code
from a much larger codebase.

Karsten
--
GPG 40BE 5B0E C98E 1713 AFA6 5BC0 3BEA AC80 7D4F C89B

1

rocksolid light 0.9.8
clearnet tor