Skip to content

Instantly share code, notes, and snippets.

@jacob414
Created May 6, 2015 10:19
Show Gist options
  • Save jacob414/4a095ab7d9b766b33eb7 to your computer and use it in GitHub Desktop.
Save jacob414/4a095ab7d9b766b33eb7 to your computer and use it in GitHub Desktop.
# My alternative to `.first_or_404()` that can also handle ValueError's (common use case for me).
# could of course be made to check for more common errors, but for now this has been what I need.
from flask import abort
def vcoerce(validate_p):
"Sanitises the result of a function from ValueError's and empty results"
try:
return validate_p() or abort(404)
except ValueError:
abort(400)
if result is None:
abort(404)
# Example usage from one of my codebases:
@app.route('/edit/<name>/<sku>')
@restricted
def edit(name, sku):
return render_template('edit.html',
upload=vcoerce(lambda: db.pattern.query.filter_by( # Requires result or 404
sku=snippets.vcoerce(lambda: int(sku))) # Requires parseable as int
.first()),
form=Upload())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment