Class-based Views

This page introduces using the View and MethodView classes to write class-based views.

A class-based view is a class that acts as a view function. Because it is a class, different instances of the class can be created with different arguments, to change the behavior of the view. This is also known as generic, reusable, or pluggable views.

An example of where this is useful is defining a class that creates an API based on the database model it is initialized with.

For more complex API behavior and customization, look into the various API extensions for Flask.

Basic Reusable View

Let’s walk through an example converting a view function to a view class. We start with a view function that queries a list of users then renders a template to show the list.

  1. @app.route("/users/")
  2. def user_list():
  3. users = User.query.all()
  4. return render_template("users.html", users=users)

This works for the user model, but let’s say you also had more models that needed list pages. You’d need to write another view function for each model, even though the only thing that would change is the model and template name.

Instead, you can write a View subclass that will query a model and render a template. As the first step, we’ll convert the view to a class without any customization.

  1. from flask.views import View
  2. class UserList(View):
  3. def dispatch_request(self):
  4. users = User.query.all()
  5. return render_template("users.html", objects=users)
  6. app.add_url_rule("/users/", view_func=UserList.as_view("user_list"))

The View.dispatch_request() method is the equivalent of the view function. Calling View.as_view() method will create a view function that can be registered on the app with its add_url_rule() method. The first argument to as_view is the name to use to refer to the view with url_for().

Note

You can’t decorate the class with @app.route() the way you’d do with a basic view function.

Next, we need to be able to register the same view class for different models and templates, to make it more useful than the original function. The class will take two arguments, the model and template, and store them on self. Then dispatch_request can reference these instead of hard-coded values.

  1. class ListView(View):
  2. def __init__(self, model, template):
  3. self.model = model
  4. self.template = template
  5. def dispatch_request(self):
  6. items = self.model.query.all()
  7. return render_template(self.template, items=items)

Remember, we create the view function with View.as_view() instead of creating the class directly. Any extra arguments passed to as_view are then passed when creating the class. Now we can register the same view to handle multiple models.

  1. app.add_url_rule(
  2. "/users/",
  3. view_func=ListView.as_view("user_list", User, "users.html"),
  4. )
  5. app.add_url_rule(
  6. "/stories/",
  7. view_func=ListView.as_view("story_list", Story, "stories.html"),
  8. )

URL Variables

Any variables captured by the URL are passed as keyword arguments to the dispatch_request method, as they would be for a regular view function.

  1. class DetailView(View):
  2. def __init__(self, model):
  3. self.model = model
  4. self.template = f"{model.__name__.lower()}/detail.html"
  5. def dispatch_request(self, id)
  6. item = self.model.query.get_or_404(id)
  7. return render_template(self.template, item=item)
  8. app.add_url_rule("/users/<int:id>", view_func=DetailView.as_view("user_detail"))

View Lifetime and self

By default, a new instance of the view class is created every time a request is handled. This means that it is safe to write other data to self during the request, since the next request will not see it, unlike other forms of global state.

However, if your view class needs to do a lot of complex initialization, doing it for every request is unnecessary and can be inefficient. To avoid this, set View.init_every_request to False, which will only create one instance of the class and use it for every request. In this case, writing to self is not safe. If you need to store data during the request, use g instead.

In the ListView example, nothing writes to self during the request, so it is more efficient to create a single instance.

  1. class ListView(View):
  2. init_every_request = False
  3. def __init__(self, model, template):
  4. self.model = model
  5. self.template = template
  6. def dispatch_request(self):
  7. items = self.model.query.all()
  8. return render_template(self.template, items=items)

Different instances will still be created each for each as_view call, but not for each request to those views.

View Decorators

The view class itself is not the view function. View decorators need to be applied to the view function returned by as_view, not the class itself. Set View.decorators to a list of decorators to apply.

  1. class UserList(View):
  2. decorators = [cache(minutes=2), login_required]
  3. app.add_url_rule('/users/', view_func=UserList.as_view())

If you didn’t set decorators, you could apply them manually instead. This is equivalent to:

  1. view = UserList.as_view("users_list")
  2. view = cache(minutes=2)(view)
  3. view = login_required(view)
  4. app.add_url_rule('/users/', view_func=view)

Keep in mind that order matters. If you’re used to @decorator style, this is equivalent to:

  1. @app.route("/users/")
  2. @login_required
  3. @cache(minutes=2)
  4. def user_list():
  5. ...

Method Hints

A common pattern is to register a view with methods=["GET", "POST"], then check request.method == "POST" to decide what to do. Setting View.methods is equivalent to passing the list of methods to add_url_rule or route.

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

This is equivalent to the following, except further subclasses can inherit or change the methods.

  1. app.add_url_rule(
  2. "/my-view",
  3. view_func=MyView.as_view("my-view"),
  4. methods=["GET", "POST"],
  5. )

Method Dispatching and APIs

For APIs it can be helpful to use a different function for each HTTP method. MethodView extends the basic View to dispatch to different methods of the class based on the request method. Each HTTP method maps to a method of the class with the same (lowercase) name.

MethodView automatically sets View.methods based on the methods defined by the class. It even knows how to handle subclasses that override or define other methods.

We can make a generic ItemAPI class that provides get (detail), patch (edit), and delete methods for a given model. A GroupAPI can provide get (list) and post (create) methods.

  1. from flask.views import MethodView
  2. class ItemAPI(MethodView):
  3. init_every_request = False
  4. def __init__(self, model):
  5. self.model
  6. self.validator = generate_validator(model)
  7. def _get_item(self, id):
  8. return self.model.query.get_or_404(id)
  9. def get(self, id):
  10. user = self._get_item(id)
  11. return jsonify(item.to_json())
  12. def patch(self, id):
  13. item = self._get_item(id)
  14. errors = self.validator.validate(item, request.json)
  15. if errors:
  16. return jsonify(errors), 400
  17. item.update_from_json(request.json)
  18. db.session.commit()
  19. return jsonify(item.to_json())
  20. def delete(self, id):
  21. item = self._get_item(id)
  22. db.session.delete(item)
  23. db.session.commit()
  24. return "", 204
  25. class GroupAPI(MethodView):
  26. init_every_request = False
  27. def __init__(self, model):
  28. self.model = model
  29. self.validator = generate_validator(model, create=True)
  30. def get(self):
  31. items = self.model.query.all()
  32. return jsonify([item.to_json() for item in items])
  33. def post(self):
  34. errors = self.validator.validate(request.json)
  35. if errors:
  36. return jsonify(errors), 400
  37. db.session.add(self.model.from_json(request.json))
  38. db.session.commit()
  39. return jsonify(item.to_json())
  40. def register_api(app, model, url):
  41. app.add_url_rule(f"/{name}/<int:id>", view_func=ItemAPI(f"{name}-item", model))
  42. app.add_url_rule(f"/{name}/", view_func=GroupAPI(f"{name}-group", model))
  43. register_api(app, User, "users")
  44. register_api(app, Story, "stories")

This produces the following views, a standard REST API!

URL

Method

Description

/users/

GET

List all users

/users/

POST

Create a new user

/users/<id>

GET

Show a single user

/users/<id>

PATCH

Update a user

/users/<id>

DELETE

Delete a user

/stories/

GET

List all stories

/stories/

POST

Create a new story

/stories/<id>

GET

Show a single story

/stories/<id>

PATCH

Update a story

/stories/<id>

DELETE

Delete a story