What's the best way to write generic views using the Flask web framework?
Does the @app.route decorator support callable classes? Or am I thinking about this in entirely the wrong fashion?
Any help or advice would be greatly appreciated!
Flask 0.7 introduces pluggable views inspired by the generic views from Django which are based on classes instead of functions. The main intention is that you can replace parts of the implementations and this way have customizable pluggable views.
A view function is the code you write to respond to requests to your application. Flask uses patterns to match the incoming request URL to the view that should handle it. The view returns data that Flask turns into an outgoing response.
A view is a callable which takes a request and returns a response. This can be more than just a function, and Django provides an example of some classes which can be used as views. These allow you to structure your views and reuse code by harnessing inheritance and mixins.
Class-based views are the alternatives of function-based views. It is implemented in the projects as Python objects instead of functions. Class-based views don't replace function-based views, but they do have certain advantages over function-based views.
Starting with Python 2.6 you can apply the decorators to classes as well. There is no builtin pattern for callable classes because there are too many ways to implement them, but essentially the trick would be to override __call__
on the class and to have a wrapper decorator that instanciates the class.
I was planning on having a class-based-view extension but so far nobody came up with some good behavior for it :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With