Source code for pythonie.blueprints.signals
"""Signals let you change the behaviour of your app or blueprint
"""
import flask
blueprint = flask.Blueprint("signals", __name__)
@blueprint.before_request
[docs]def authenticate():
"""Performs authentication based on HTTP params
Looks for a password param.
"""
if not flask.request.args.get("password") == "sekret":
flask.abort(403)
# Example of setting something in the flask request globals
flask.g.password = flask.request.args["password"]
@blueprint.errorhandler(TypeError)
[docs]def handle_errors(e):
"""Ensure exceptions always return JSON errors
Note how this is registered with either an exception type or a HTTP code.
"""
response = flask.jsonify({"error": str(e)})
response.status_code = 500
return response
@blueprint.route("/")
[docs]def index():
"""A simple demo of authentication
To see in action go to http://building-webapps-with-flask.herokuapp.com/signals/?password=sekret
"""
return flask.jsonify({"message": "You got here!", "password": flask.g.password})
@blueprint.route("/not.json")
[docs]def notjson():
"""A simple demo of very specific error handling
To see in action go to http://building-webapps-with-flask.herokuapp.com/signals/not.json?password=sekret
"""
raise TypeError("Not json")