Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class-based (generic) views in Flask

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!

like image 502
Alistair Avatar asked May 03 '11 13:05

Alistair


People also ask

Does Flask have class-based views?

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.

What are views in Flask?

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.

What are class-based views?

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.

What is the difference between function based and class-based views?

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.


1 Answers

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 :)

like image 95
Armin Ronacher Avatar answered Oct 19 '22 23:10

Armin Ronacher