From 2a3e513eabf40d01b71647697093da303d2e9ce8 Mon Sep 17 00:00:00 2001 From: Changaco Date: Mon, 1 Sep 2014 18:14:44 +0200 Subject: [PATCH] simplify functions that take an optional cursor --- gratipay/models/__init__.py | 14 ++++++++++++++ gratipay/models/participant.py | 18 ++---------------- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/gratipay/models/__init__.py b/gratipay/models/__init__.py index 815737c669..b3ed6bb79d 100644 --- a/gratipay/models/__init__.py +++ b/gratipay/models/__init__.py @@ -6,12 +6,26 @@ everything on Gratipay. """ +from contextlib import contextmanager + from postgres import Postgres import psycopg2.extras +@contextmanager +def just_yield(obj): + yield obj + + class GratipayDB(Postgres): + def get_cursor(self, cursor=None, **kw): + if cursor: + if kw: + raise ValueError('cannot change options when reusing a cursor') + return just_yield(cursor) + return super(GratipayDB, self).get_cursor(**kw) + def self_check(self): with self.get_cursor() as cursor: check_db(cursor) diff --git a/gratipay/models/participant.py b/gratipay/models/participant.py index e362ef3f61..add2cd38fe 100644 --- a/gratipay/models/participant.py +++ b/gratipay/models/participant.py @@ -567,11 +567,7 @@ def update_goal(self, goal): self.update_receiving(c) def update_is_closed(self, is_closed, cursor=None): - ctx = None - if cursor is None: - ctx = self.db.get_cursor() - cursor = ctx.__enter__() - try: + with self.db.get_cursor(cursor) as cursor: cursor.run( "UPDATE participants SET is_closed=%(is_closed)s " "WHERE username=%(username)s" , dict(username=self.username, is_closed=is_closed) @@ -581,9 +577,6 @@ def update_is_closed(self, is_closed, cursor=None): , dict(id=self.id, action='set', values=dict(is_closed=is_closed)) ) self.set_attributes(is_closed=is_closed) - finally: - if ctx is not None: - ctx.__exit__(None, None, None) def update_giving(self, cursor=None): giving = (cursor or self.db).one(""" @@ -649,11 +642,7 @@ def update_receiving(self, cursor=None): self.update_taking(old_takes, new_takes, cursor=cursor) def update_is_free_rider(self, is_free_rider, cursor=None): - ctx = None - if cursor is None: - ctx = self.db.get_cursor() - cursor = ctx.__enter__() - try: + with self.db.get_cursor(cursor) as cursor: cursor.run( "UPDATE participants SET is_free_rider=%(is_free_rider)s " "WHERE username=%(username)s" , dict(username=self.username, is_free_rider=is_free_rider) @@ -663,9 +652,6 @@ def update_is_free_rider(self, is_free_rider, cursor=None): , dict(id=self.id, action='set', values=dict(is_free_rider=is_free_rider)) ) self.set_attributes(is_free_rider=is_free_rider) - finally: - if ctx is not None: - ctx.__exit__(None, None, None) def set_tip_to(self, tippee, amount, update_self=True, update_tippee=True, cursor=None):