Just watched first 10 minutes of Miguel’s Flask talk. It’s fantastic. He’s addressed so many of the bugbears I’ve encountered while developing Python web-apps… Read on to learn more.
- A decorator to restrict the HTTP verbs that apply (“GET” in the example below)
- Use the same decorator to specify the URL’s “action” (“/students” in the example below)
- Allows methods themselves to be called whatever; could even be arbitary lambdas (“getStudents” in the example below)
to_json(); an instance method
- Because more and more, everything is becoming an API. APIs increasingly use JSON.
- If a class has this method, Flask can covnert it to a Python dict. Python dict is easily translated to JSON.
- In my homebrewed solution I called this the js() method; I gave it to any class that I might pass around in an API
s = Student.query.get_or_404()
jsonify(); a Flask app convenience function
- Seen in the above example; makes sure the output is sent with appropriate headers?
- In my homebrewed solution I gave my webApp2 Handler a jsonResponse() method.
- My homebrewed jsonResponse method would also call the to_json() equivalent using a custom JSONEncoder
- Only recently I realize deserializing (i.e. from JSON to Python model) is just-as-important (if not more important than) than serializing (from model to JSON)
- In the Flask example, it deserializes — from form’s submitted with a POST request — to models (like Student) it can put directly into SQL Alchemy
- Useful not only for interpreting request data delivered in a JSON payload, but also for deserializing items stored in key-value (mem)cache
- (vs depickling them with __getstate__ and __setstate__ methods)
Syntax for path-matching
- I use C# at work extensively. This reminds me of C# route constraints
- Google App Engine provides webapp2; which supports a pretty comprehensive syntax also
- Flask goes above-and-beyond by allowing me to specify types. Casting a request payload to the right types is especially helpful.
- Looks like only primitive types are supported?
Use of Native HTTP API
- Using a response of headers[‘Location’]
To provide information about the location of a newly created resource. In this circumstance, the Location header should be sent with an HTTP status code of 201 or 202.
- …and status code 201
The request has been fulfilled and resulted in a new resource being created.
This isn’t Flask-specific; these status codes are established by standards bodies and should be addable with any framework.
But I’m excited about Flask, so I wanted to share! Do you have any successes? I can point to one huge success: RankAndFiled.com