Skip to content

Commit

Permalink
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
♻️ Restructure try/except blocks in resource class
Browse files Browse the repository at this point in the history
znatty22 committed Feb 1, 2018

Verified

This commit was signed with the committer’s verified signature.
morozov Sergei Morozov
1 parent c3862e3 commit eeecf1f
Showing 1 changed file with 30 additions and 14 deletions.
44 changes: 30 additions & 14 deletions dataservice/api/demographic/resources.py
Original file line number Diff line number Diff line change
@@ -25,6 +25,7 @@ def get(self, kf_id):
Get a demographic by Kids First id or get all demographics if
Kids First id is None
"""

# Get all
if kf_id is None:
d = Demographic.query.all()
@@ -43,16 +44,20 @@ def post(self):
"""
Create a new demographic
"""

body = request.json

# Deserialize
try:
# Deserialize
d = DemographicSchema(strict=True).load(body).data
# Add to and save in database
db.session.add(d)
db.session.commit()
# Request body not valid
except ValidationError as e:
abort(400, 'could not create demographic: {}'.format(e.messages))

# Add to and save in database
try:
db.session.add(d)
db.session.commit()
# Database error
except IntegrityError as e:
db.session.rollback()
@@ -69,25 +74,33 @@ def put(self, kf_id):
Update an existing demographic given a Kids First id
"""

body = request.json

# Check if demographic exists
try:
# Check if demographic exists
d1 = Demographic.query.filter_by(kf_id=kf_id).one()
# For validation only
d = DemographicSchema(strict=True).load(body).data
# Deserialize
d1.external_id = body.get('external_id')
d1.race = body.get('race')
d1.gender = body.get('gender')
d1.ethnicity = body.get('ethnicity')
d1.participant_id = body.get('participant_id')
db.session.commit()
# Not found in database
except NoResultFound:
abort(404, 'could not find {} `{}`'.format('demographic', kf_id))

# Validation only
try:
d = DemographicSchema(strict=True).load(body).data
# Request body not valid
except ValidationError as e:
abort(400, 'could not update demographic: {}'.format(e.messages))

# Deserialize
d1.external_id = body.get('external_id')
d1.race = body.get('race')
d1.gender = body.get('gender')
d1.ethnicity = body.get('ethnicity')
d1.participant_id = body.get('participant_id')

# Save to database
try:
db.session.commit()
# Database error
except IntegrityError as e:
db.session.rollback()
@@ -104,12 +117,15 @@ def delete(self, kf_id):
Deletes a demographic given a Kids First id
"""

# Check if demographic exists
try:
d = Demographic.query.filter_by(kf_id=kf_id).one()
# Not found in database
except NoResultFound:
abort(404, 'could not find {} `{}`'.format('demographic', kf_id))

# Save in database
db.session.delete(d)
db.session.commit()

0 comments on commit eeecf1f

Please sign in to comment.