Flask
Structure of Flask App
https://www.digitalocean.com/community/tutorials/how-to-structure-large-flask-applications
https://github.com/pallets/flask/wiki/Large-app-how-to
https://github.com/Robpol86/Flask-Large-Application-Example
Make RESTful API with Flask
http://blog.luisrei.com/articles/flaskrest.html
- Create proper url (principle: everything is resource, Noun, not Verb)
- Define proper HTTP method
- Flask Request (handle client input)
- Define header
from flask import json
@app.route('/messages', methods = ['POST'])
def api_message():
if request.headers['Content-Type'] == 'text/plain':
return "Text Message: " + request.data
elif request.headers['Content-Type'] == 'application/json':
return "JSON Message: " + json.dumps(request.json)
elif request.headers['Content-Type'] == 'application/octet-stream':
f = open('./binary', 'wb')
f.write(request.data)
f.close()
return "Binary message written!"
else:
return "415 Unsupported Media Type ;)"
- Flask Response (use to return result)
- Return response according to HTTP standard
from flask import Response
@app.route('/hello', methods = ['GET'])
def api_hello():
data = {
'hello' : 'world',
'number' : 3
}
js = json.dumps(data)
resp = Response(js, status=200, mimetype='application/json')
resp.headers['Link'] = 'http://luisrei.com'
return resp
- Error handling
- Authorization
Flask-Restful
Request Parsing
Flask-RESTful’s request parsing interface, reqparse, is modeled after the argparse interface. It’s designed to provide simple and uniform access to any variable on the flask.request object in Flask.