This document introduces Flask, a Python microframework for building web applications and APIs. It shows how to create a basic "Hello World" Flask app in 3 steps: creating the Flask object, defining a route, and returning a JSON response. It then demonstrates various response types like simple text, generators, and files. It covers routing concepts like dynamic routes, default values, and REST verbs. More advanced topics discussed include static file serving, database connections, exception handling, and using blueprints to organize routes.
7. Returning a Generator
@app.route("/generator/")
def return_generator():
def loads_of_data():
yield "["
for i in xrange(5):
if i:
yield ","
yield '{ "key%d": "Entry Number %d"}' % (i, i)
yield "]"
return Response(loads_of_data(), content_type="application/json")
Generator Function
8. Returning a Response
@app.route("/response/")
def return_response():
msg = {"message": "I am working on that..."}
msg_json = json.dumps(msg)
return Response(msg_json, content_type="application/json",
status=202)
class flask.Response(response=None, status=None, headers=None,
mimetype=None,content_type=None, direct_passthrough=False)
12. Dynamic Route - Set Type
@app.route("/car/<string:make>/<int:model>")
def car(make, model):
car = {
"make": make,
"model": model
}
return jsonify(car)
Specify type of params
13. Dynamic Route - Set Default
@app.route("/car/<string:make>/<int:model>")
@app.route("/car/<string:make>/", defaults={"model": 500})
@app.route("/car/", defaults={"make": "Fiat", "model": 500})
def car(make, model):
car = {
"make": make,
"model": model
}
return jsonify(car)
14. REST Verbs
@app.route("/inventory/", methods=['POST'])
def inventory_post():
data = request.json
resp = jsonify({"idinput": data.get("id")})
resp.status_code = 201
return resp
methods allow a list of verbs
jsonify returns a Response object
18. Database Connection
from flask import g
def get_db():
db = getattr(g, '_database', None)
if db is None:
db = g._database = connect_to_database()
return db
@app.teardown_appcontext
def close_connection(exception):
db = getattr(g, '_database', None)
if db is not None:
db.close()
http://flask.pocoo.org/docs/0.10/patterns/sqlite3/
Use Flask’s Global Object
Open connection if not connected
Close connection when request is done
19. Exception Handling
def restful_error_handler(ex):
resp = jsonify(error_message=str(ex))
if isinstance(ex, HTTPException):
resp.status_code = ex.code
else:
resp.status_code = 500
return resp
for code in default_exceptions.iterkeys():
app.error_handler_spec[None][code] = restful_error_handler
http://flask.pocoo.org/snippets/83/
Set Response Code
[<blueprint name>][<http code>]
20. Blueprint
bp = Blueprint('car', __name__)
@bp.route("/<make>/<model>"):
def return_car(make, model):
return jsonify({ "make": make, "model": model})
app.register_blueprint(bp, url_prefix='/car')
Create a Blueprint object
Declare route of the blueprint
Register blueprint