A simple shortcut which let you returning an abort code when the wanted object is not found.
This kind of trick is already integrated in the Flask-SQLAlchemy extension (with the get_or_404() method) so it's just usefull if you're using SQLAlchemy natively...
Here's the code:
def get_or_abort(model, object_id, code=404):
"""
get an object with his given id or an abort error (404 is the default)
"""
result = model.query.get(object_id)
return result or abort(code)
And now how to use it in your app:
def theme_detail(theme_id):
# shows a theme
theme = get_or_abort(Theme, theme_id)
return render_template('theme_detail.html', theme=theme)
This snippet by Jérôme Pigeot can be used freely for anything you like. Consider it public domain.
Comments
Slightly improved version by Dag Odenhall on 2010-09-03 @ 20:00
abort()raises an exception and is not something you return. Also you'll want to check ifresult is Noneor you'll abort for "nonzero" values (False, 0, '', …). Don't know if this is an actual problem, butis Noneis a best practice, regardless.comment by Jérôme Pigeot on 2010-09-13 @ 20:25
thanks for the info, i'll take care to correct my code.