Last active
August 29, 2015 14:03
-
-
Save horiajurcut/91f5235a381eb0f51506 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# In the model you decide what to expose | |
__collections__ = [Bookmark] | |
# In the Model View base class the relationship is exposed | |
@route('/<int:entity_id>') | |
@route('/<int:entity_id>/<string:relationship>') | |
def get(self, entity_id, relationship=None): | |
query = self.model.query | |
model = None | |
if relationship: | |
p = inflect.engine() | |
model = p.singular_noun(relationship.capitalize()) | |
model = next((m for m in self.model.__collections__ \ | |
if m.__name__ == model), None) | |
if model: | |
column = '%s_id' % (self.model.__name__.lower()) | |
items = model.query.filter( | |
getattr(model, column) == entity_id | |
).all() | |
items = [AlchemyDecoder( | |
item, | |
item.__exclude_collection__, | |
item.__eager_collection__ | |
) for item in items] | |
return items | |
elif relationship: | |
raise HttpNotFound({ | |
'error': 'Relationship not found in database' | |
}) | |
for backref in self.model.__eager__: | |
query = query.options(self.db.joinedload(backref)) | |
item = query.filter_by(id=entity_id).first() | |
if item: | |
return AlchemyDecoder(item, item.__exclude__, item.__eager__) | |
else: | |
raise HttpNotFound({'error': 'Item not found in database'}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment