Flask Snippets

Snippets are unofficial and unmaintained.

This is an archived view of user-submitted snippets. Despite being hosted on the Flask site, they are not official. No Flask maintainer has curated or checked the snippets for security, correctness, or design.

Getting an object from a SQLAlchemy model or abort

Posted by Jérôme Pigeot on 2010-08-24 @ 11:32 and filed in Database

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)
    if result is None:
    return result

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.