Create utility function for the pattern of committing to the database or raising AlreadyExistsError

This commit is contained in:
leigh-mil
2019-12-16 10:39:47 -05:00
parent afad5362a1
commit b927ef1b0e
3 changed files with 20 additions and 33 deletions

View File

@@ -1,5 +1,10 @@
import re
from sqlalchemy.exc import IntegrityError
from atst.database import db
from atst.domain.exceptions import AlreadyExistsError
def first_or_none(predicate, lst):
return next((x for x in lst if predicate(x)), None)
@@ -23,3 +28,11 @@ def camel_to_snake(camel_cased):
def pick(keys, dct):
_keys = set(keys)
return {k: v for (k, v) in dct.items() if k in _keys}
def update_or_raise_already_exists_error(message):
try:
db.session.commit()
except IntegrityError:
db.session.rollback()
raise AlreadyExistsError(message)