Pluggable Views

Changelog

New in version 0.7.

Flask 0.7 introduces pluggable views inspired by the generic views fromDjango which are based on classes instead of functions. The mainintention is that you can replace parts of the implementations and thisway have customizable pluggable views.

Basic Principle

Consider you have a function that loads a list of objects from thedatabase and renders into a template:

  1. @app.route('/users/')def show_users(page): users = User.query.all() return render_template('users.html', users=users)

This is simple and flexible, but if you want to provide this view in ageneric fashion that can be adapted to other models and templates as wellyou might want more flexibility. This is where pluggable class-basedviews come into place. As the first step to convert this into a classbased view you would do this:

  1. from flask.views import View
  2.  
  3. class ShowUsers(View):
  4.  
  5. def dispatch_request(self):
  6. users = User.query.all()
  7. return render_template('users.html', objects=users)
  8.  
  9. app.add_url_rule('/users/', view_func=ShowUsers.as_view('show_users'))

As you can see what you have to do is to create a subclass offlask.views.View and implementdispatch_request(). Then we have to convert thatclass into an actual view function by using theas_view() class method. The string you pass tothat function is the name of the endpoint that view will then have. Butthis by itself is not helpful, so let’s refactor the code a bit:

  1. from flask.views import View
  2.  
  3. class ListView(View):
  4.  
  5. def get_template_name(self):
  6. raise NotImplementedError()
  7.  
  8. def render_template(self, context):
  9. return render_template(self.get_template_name(), **context)
  10.  
  11. def dispatch_request(self):
  12. context = {'objects': self.get_objects()}
  13. return self.render_template(context)
  14.  
  15. class UserView(ListView):
  16.  
  17. def get_template_name(self):
  18. return 'users.html'
  19.  
  20. def get_objects(self):
  21. return User.query.all()

This of course is not that helpful for such a small example, but it’s goodenough to explain the basic principle. When you have a class-based viewthe question comes up what self points to. The way this works is thatwhenever the request is dispatched a new instance of the class is createdand the dispatch_request() method is called withthe parameters from the URL rule. The class itself is instantiated withthe parameters passed to the as_view() function.For instance you can write a class like this:

  1. class RenderTemplateView(View):
  2. def __init__(self, template_name):
  3. self.template_name = template_name
  4. def dispatch_request(self):
  5. return render_template(self.template_name)

And then you can register it like this:

  1. app.add_url_rule('/about', view_func=RenderTemplateView.as_view(
  2. 'about_page', template_name='about.html'))

Method Hints

Pluggable views are attached to the application like a regular function byeither using route() or betteradd_url_rule(). That however also means that you wouldhave to provide the names of the HTTP methods the view supports when youattach this. In order to move that information to the class you canprovide a methods attribute that has thisinformation:

  1. class MyView(View):
  2. methods = ['GET', 'POST']
  3.  
  4. def dispatch_request(self):
  5. if request.method == 'POST':
  6. ...
  7. ...
  8.  
  9. app.add_url_rule('/myview', view_func=MyView.as_view('myview'))

Method Based Dispatching

For RESTful APIs it’s especially helpful to execute a different functionfor each HTTP method. With the flask.views.MethodView you caneasily do that. Each HTTP method maps to a function with the same name(just in lowercase):

  1. from flask.views import MethodView
  2.  
  3. class UserAPI(MethodView):
  4.  
  5. def get(self):
  6. users = User.query.all()
  7. ...
  8.  
  9. def post(self):
  10. user = User.from_form_data(request.form)
  11. ...
  12.  
  13. app.add_url_rule('/users/', view_func=UserAPI.as_view('users'))

That way you also don’t have to provide themethods attribute. It’s automatically set basedon the methods defined in the class.

Decorating Views

Since the view class itself is not the view function that is added to therouting system it does not make much sense to decorate the class itself.Instead you either have to decorate the return value ofas_view() by hand:

  1. def user_required(f):
  2. """Checks whether user is logged in or raises error 401."""
  3. def decorator(*args, **kwargs):
  4. if not g.user:
  5. abort(401)
  6. return f(*args, **kwargs)
  7. return decorator
  8.  
  9. view = user_required(UserAPI.as_view('users'))
  10. app.add_url_rule('/users/', view_func=view)

Starting with Flask 0.8 there is also an alternative way where you canspecify a list of decorators to apply in the class declaration:

  1. class UserAPI(MethodView):
  2. decorators = [user_required]

Due to the implicit self from the caller’s perspective you cannot useregular view decorators on the individual methods of the view however,keep this in mind.

Method Views for APIs

Web APIs are often working very closely with HTTP verbs so it makes a lotof sense to implement such an API based on theMethodView. That said, you will notice that the APIwill require different URL rules that go to the same method view most ofthe time. For instance consider that you are exposing a user object onthe web:

URLMethodDescription
/users/GETGives a list of all users
/users/POSTCreates a new user
/users/<id>GETShows a single user
/users/<id>PUTUpdates a single user
/users/<id>DELETEDeletes a single user

So how would you go about doing that with theMethodView? The trick is to take advantage of thefact that you can provide multiple rules to the same view.

Let’s assume for the moment the view would look like this:

  1. class UserAPI(MethodView):
  2.  
  3. def get(self, user_id):
  4. if user_id is None:
  5. # return a list of users
  6. pass
  7. else:
  8. # expose a single user
  9. pass
  10.  
  11. def post(self):
  12. # create a new user
  13. pass
  14.  
  15. def delete(self, user_id):
  16. # delete a single user
  17. pass
  18.  
  19. def put(self, user_id):
  20. # update a single user
  21. pass

So how do we hook this up with the routing system? By adding two rulesand explicitly mentioning the methods for each:

  1. user_view = UserAPI.as_view('user_api')
  2. app.add_url_rule('/users/', defaults={'user_id': None},
  3. view_func=user_view, methods=['GET',])
  4. app.add_url_rule('/users/', view_func=user_view, methods=['POST',])
  5. app.add_url_rule('/users/<int:user_id>', view_func=user_view,
  6. methods=['GET', 'PUT', 'DELETE'])

If you have a lot of APIs that look similar you can refactor thatregistration code:

  1. def register_api(view, endpoint, url, pk='id', pk_type='int'):
  2. view_func = view.as_view(endpoint)
  3. app.add_url_rule(url, defaults={pk: None},
  4. view_func=view_func, methods=['GET',])
  5. app.add_url_rule(url, view_func=view_func, methods=['POST',])
  6. app.add_url_rule('%s<%s:%s>' % (url, pk_type, pk), view_func=view_func,
  7. methods=['GET', 'PUT', 'DELETE'])
  8.  
  9. register_api(UserAPI, 'user_api', '/users/', pk='user_id')