Skip to content
This repository has been archived by the owner on Feb 8, 2018. It is now read-only.

Commit

Permalink
simplify functions that take an optional cursor
Browse files Browse the repository at this point in the history
  • Loading branch information
Changaco authored and chadwhitacre committed Sep 23, 2014
1 parent a33f590 commit 2a3e513
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 16 deletions.
14 changes: 14 additions & 0 deletions gratipay/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
18 changes: 2 additions & 16 deletions gratipay/models/participant.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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("""
Expand Down Expand Up @@ -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)
Expand All @@ -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):
Expand Down

0 comments on commit 2a3e513

Please sign in to comment.