18. Class-Based Views¶
New in version 0.7.
Alternative way to use view functions. A subclass has to implement
dispatch_request()which is called with the view arguments from the URL routing system. If
methodsis provided the methods do not have to be passed to the
class MyView(View): methods = ['GET'] def dispatch_request(self, name): return 'Hello %s!' % name app.add_url_rule('/hello/<name>', view_func=MyView.as_view('myview'))
When you want to decorate a pluggable view you will have to either do that when the view function is created (by wrapping the return value of
as_view()) or you can use the
class SecretView(View): methods = ['GET'] decorators = [superuser_required] def dispatch_request(self): ...
The decorators stored in the decorators list are applied one after another when the view function is created. Note that you can not use the class based decorators since those would decorate the view class and not the generated view function!
as_view(name, *class_args, **class_kwargs)¶
Converts the class into an actual view function that can be used with the routing system. Internally this generates a function on the fly which will instantiate the
Viewon each request and call the
dispatch_request()method on it.
The arguments passed to
as_view()are forwarded to the constructor of the class.
The canonical way to decorate class-based views is to decorate the return value of as_view(). However since this moves parts of the logic from the class declaration to the place where it’s hooked into the routing system.
You can place one or more decorators in this list and whenever the view function is created the result is automatically decorated.
New in version 0.8.
Subclasses have to override this method to implement the actual view function code. This method is called with all the arguments from the URL rule.
A list of methods this view can handle.
Like a regular class-based view but that dispatches requests to particular methods. For instance if you implement a method called
get()it means you will response to
'GET'requests and the
dispatch_request()implementation will automatically forward your request to that. Also
optionsis set for you automatically:
class CounterAPI(MethodView): def get(self): return session.get('counter', 0) def post(self): session['counter'] = session.get('counter', 0) + 1 return 'OK' app.add_url_rule('/counter', view_func=CounterAPI.as_view('counter'))