Skip to content

Instantly share code, notes, and snippets.

@Jwpe
Created February 16, 2014 04:03
Show Gist options
  • Save Jwpe/9029046 to your computer and use it in GitHub Desktop.
Save Jwpe/9029046 to your computer and use it in GitHub Desktop.
Comparison of decorator and Flask builtins
from flask import Flask, jsonify, abort, g
import flask_nicely
from flask_nicely.errors import NotFound
app = Flask(__name__)
### With decorator ###
# JSON response view
@app.route('/hello/<name>')
@flask_nicely.nice_json
def hello(name):
data = {
"Name": name,
"Message": "Hello, {}!".format(name)
}
return data
# Exception view
@app.route('/error/404')
@flask_nicely.nice_json
def throw_404():
raise NotFound("Could not find the grail!")
### Without decorator ###
# JSON response view
@app.route('/hello2/<name>')
def hello_two(name):
data = {
"Name": name,
"Message": "Hello, {}!".format(name)
}
return jsonify(data=data, status=200, error=None)
# Error handler
@app.errorhandler(404)
def page_not_found(error):
data = {
"error": g.get('custom_error_message'),
"status": error.code,
"data": None
}
response = jsonify(data)
response.status_code = 404
return response
# Exception view
@app.route('/error2/404')
def throw_404_two():
g.custom_error_message = "Could not find the grail!"
abort(404)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment