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.

get_object_or_404

Posted by Vitaliy Shishorin on 2013-07-25 @ 20:56 and filed in Database

from sqlalchemy.orm import exc
from werkzeug.exceptions import abort

def get_object_or_404(model, *criterion):
    try:
        return model.query.filter(*criterion).one()
    except exc.NoResultFound, exc.MultipleResultsFound:
        abort(404)

Example:

board = get_object_or_404(Board, Board.slug == slug)

or

user = get_object_or_404(User, User.id == id)

This snippet by Vitaliy Shishorin can be used freely for anything you like. Consider it public domain.