rewrite class-based view docs
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by David Lord · parent 6e23239 · Browse files · 2 files·+305 added−209 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+305 added−209 removed
- other:+305 added−209 removed
Provenance
- Commit
bab5a65- Tree
e4bcfa1- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
6e23239
2 files changed+305 added−209 removed
modified:docs/views.rst+249 added-165 removed
1-Pluggable Views2-===============1+Class-based Views2+=================3 4-.. versionadded:: 0.74+.. currentmodule:: flask.views5 6-Flask 0.7 introduces pluggable views inspired by the generic views from7-Django which are based on classes instead of functions. The main8-intention is that you can replace parts of the implementations and this9-way have customizable pluggable views.6+This page introduces using the :class:`View` and :class:`MethodView`7+classes to write class-based views.8 11-Basic Principle12----------------9+A class-based view is a class that acts as a view function. Because it10+is a class, different instances of the class can be created with11+different arguments, to change the behavior of the view. This is also12+known as generic, reusable, or pluggable views.13 14-Consider you have a function that loads a list of objects from the15-database and renders into a template::14+An example of where this is useful is defining a class that creates an15+API based on the database model it is initialized with.16 17- @app.route('/users/')18- def show_users(page):17+For more complex API behavior and customization, look into the various18+API extensions for Flask.19+20+21+Basic Reusable View22+-------------------23+24+Let's walk through an example converting a view function to a view25+class. We start with a view function that queries a list of users then26+renders a template to show the list.27+28+.. code-block:: python29+30+ @app.route("/users/")31+ def user_list():32 users = User.query.all()20- return render_template('users.html', users=users)33+ return render_template("users.html", users=users)34 22-This is simple and flexible, but if you want to provide this view in a23-generic fashion that can be adapted to other models and templates as well24-you might want more flexibility. This is where pluggable class-based25-views come into place. As the first step to convert this into a class26-based view you would do this::35+This works for the user model, but let's say you also had more models36+that needed list pages. You'd need to write another view function for37+each model, even though the only thing that would change is the model38+and template name.39 40+Instead, you can write a :class:`View` subclass that will query a model41+and render a template. As the first step, we'll convert the view to a42+class without any customization.43 44+.. code-block:: python45+46 from flask.views import View47 31- class ShowUsers(View):32-48+ class UserList(View):49 def dispatch_request(self):50 users = User.query.all()35- return render_template('users.html', objects=users)51+ return render_template("users.html", objects=users)52 37- app.add_url_rule('/users/', view_func=ShowUsers.as_view('show_users'))53+ app.add_url_rule("/users/", view_func=UserList.as_view("user_list"))54 39-As you can see what you have to do is to create a subclass of40-:class:`flask.views.View` and implement41-:meth:`~flask.views.View.dispatch_request`. Then we have to convert that42-class into an actual view function by using the43-:meth:`~flask.views.View.as_view` class method. The string you pass to44-that function is the name of the endpoint that view will then have. But45-this by itself is not helpful, so let's refactor the code a bit::55+The :meth:`View.dispatch_request` method is the equivalent of the view56+function. Calling :meth:`View.as_view` method will create a view57+function that can be registered on the app with its58+:meth:`~flask.Flask.add_url_rule` method. The first argument to59+``as_view`` is the name to use to refer to the view with60+:func:`~flask.url_for`.61 62+.. note::63 48- from flask.views import View64+ You can't decorate the class with ``@app.route()`` the way you'd65+ do with a basic view function.66 50- class ListView(View):67+Next, we need to be able to register the same view class for different68+models and templates, to make it more useful than the original function.69+The class will take two arguments, the model and template, and store70+them on ``self``. Then ``dispatch_request`` can reference these instead71+of hard-coded values.72 52- def get_template_name(self):53- raise NotImplementedError()73+.. code-block:: python74 55- def render_template(self, context):56- return render_template(self.get_template_name(), **context)75+ class ListView(View):76+ def __init__(self, model, template):77+ self.model = model78+ self.template = template79 80 def dispatch_request(self):59- context = {'objects': self.get_objects()}60- return self.render_template(context)81+ items = self.model.query.all()82+ return render_template(self.template, items=items)83 62- class UserView(ListView):84+Remember, we create the view function with ``View.as_view()`` instead of85+creating the class directly. Any extra arguments passed to ``as_view``86+are then passed when creating the class. Now we can register the same87+view to handle multiple models.88 64- def get_template_name(self):65- return 'users.html'89+.. code-block:: python90 67- def get_objects(self):68- return User.query.all()91+ app.add_url_rule(92+ "/users/",93+ view_func=ListView.as_view("user_list", User, "users.html"),94+ )95+ app.add_url_rule(96+ "/stories/",97+ view_func=ListView.as_view("story_list", Story, "stories.html"),98+ )99 70-This of course is not that helpful for such a small example, but it's good71-enough to explain the basic principle. When you have a class-based view72-the question comes up what ``self`` points to. The way this works is that73-whenever the request is dispatched a new instance of the class is created74-and the :meth:`~flask.views.View.dispatch_request` method is called with75-the parameters from the URL rule. The class itself is instantiated with76-the parameters passed to the :meth:`~flask.views.View.as_view` function.77-For instance you can write a class like this::100 79- class RenderTemplateView(View):80- def __init__(self, template_name):81- self.template_name = template_name101+URL Variables102+-------------103+104+Any variables captured by the URL are passed as keyword arguments to the105+``dispatch_request`` method, as they would be for a regular view106+function.107+108+.. code-block:: python109+110+ class DetailView(View):111+ def __init__(self, model):112+ self.model = model113+ self.template = f"{model.__name__.lower()}/detail.html"114+115+ def dispatch_request(self, id)116+ item = self.model.query.get_or_404(id)117+ return render_template(self.template, item=item)118+119+ app.add_url_rule("/users/<int:id>", view_func=DetailView.as_view("user_detail"))120+121+122+View Lifetime and ``self``123+--------------------------124+125+By default, a new instance of the view class is created every time a126+request is handled. This means that it is safe to write other data to127+``self`` during the request, since the next request will not see it,128+unlike other forms of global state.129+130+However, if your view class needs to do a lot of complex initialization,131+doing it for every request is unnecessary and can be inefficient. To132+avoid this, set :attr:`View.init_every_request` to ``False``, which will133+only create one instance of the class and use it for every request. In134+this case, writing to ``self`` is not safe. If you need to store data135+during the request, use :data:`~flask.g` instead.136+137+In the ``ListView`` example, nothing writes to ``self`` during the138+request, so it is more efficient to create a single instance.139+140+.. code-block:: python141+142+ class ListView(View):143+ init_every_request = False144+145+ def __init__(self, model, template):146+ self.model = model147+ self.template = template148+149 def dispatch_request(self):150+ items = self.model.query.all()83- return render_template(self.template_name)151+ return render_template(self.template, items=items)152 85-And then you can register it like this::153+Different instances will still be created each for each ``as_view``154+call, but not for each request to those views.155 87- app.add_url_rule('/about', view_func=RenderTemplateView.as_view(88- 'about_page', template_name='about.html'))156 157+View Decorators158+---------------159+160+The view class itself is not the view function. View decorators need to161+be applied to the view function returned by ``as_view``, not the class162+itself. Set :attr:`View.decorators` to a list of decorators to apply.163+164+.. code-block:: python165+166+ class UserList(View):167+ decorators = [cache(minutes=2), login_required]168+169+ app.add_url_rule('/users/', view_func=UserList.as_view())170+171+If you didn't set ``decorators``, you could apply them manually instead.172+This is equivalent to:173+174+.. code-block:: python175+176+ view = UserList.as_view("users_list")177+ view = cache(minutes=2)(view)178+ view = login_required(view)179+ app.add_url_rule('/users/', view_func=view)180+181+Keep in mind that order matters. If you're used to ``@decorator`` style,182+this is equivalent to:183+184+.. code-block:: python185+186+ @app.route("/users/")187+ @login_required188+ @cache(minutes=2)189+ def user_list():190+ ...191+192+193 Method Hints194 ------------195 93-Pluggable views are attached to the application like a regular function by94-either using :func:`~flask.Flask.route` or better95-:meth:`~flask.Flask.add_url_rule`. That however also means that you would96-have to provide the names of the HTTP methods the view supports when you97-attach this. In order to move that information to the class you can98-provide a :attr:`~flask.views.View.methods` attribute that has this99-information::196+A common pattern is to register a view with ``methods=["GET", "POST"]``,197+then check ``request.method == "POST"`` to decide what to do. Setting198+:attr:`View.methods` is equivalent to passing the list of methods to199+``add_url_rule`` or ``route``.200 201+.. code-block:: python202+203 class MyView(View):102- methods = ['GET', 'POST']204+ methods = ["GET", "POST"]205 206 def dispatch_request(self):105- if request.method == 'POST':207+ if request.method == "POST":208 ...209 ...210 109- app.add_url_rule('/myview', view_func=MyView.as_view('myview'))211+ app.add_url_rule('/my-view', view_func=MyView.as_view('my-view'))212 111-Method Based Dispatching112-------------------------213+This is equivalent to the following, except further subclasses can214+inherit or change the methods.215 114-For RESTful APIs it's especially helpful to execute a different function115-for each HTTP method. With the :class:`flask.views.MethodView` you can116-easily do that. Each HTTP method maps to a method of the class with the117-same name (just in lowercase)::216+.. code-block:: python217 119- from flask.views import MethodView218+ app.add_url_rule(219+ "/my-view",220+ view_func=MyView.as_view("my-view"),221+ methods=["GET", "POST"],222+ )223 121- class UserAPI(MethodView):224 123- def get(self):124- users = User.query.all()125- ...225+Method Dispatching and APIs226+---------------------------227 127- def post(self):128- user = User.from_form_data(request.form)129- ...228+For APIs it can be helpful to use a different function for each HTTP229+method. :class:`MethodView` extends the basic :class:`View` to dispatch230+to different methods of the class based on the request method. Each HTTP231+method maps to a method of the class with the same (lowercase) name.232 131- app.add_url_rule('/users/', view_func=UserAPI.as_view('users'))233+:class:`MethodView` automatically sets :attr:`View.methods` based on the234+methods defined by the class. It even knows how to handle subclasses235+that override or define other methods.236 133-That way you also don't have to provide the134-:attr:`~flask.views.View.methods` attribute. It's automatically set based135-on the methods defined in the class.237+We can make a generic ``ItemAPI`` class that provides get (detail),238+patch (edit), and delete methods for a given model. A ``GroupAPI`` can239+provide get (list) and post (create) methods.240 137-Decorating Views138-----------------241+.. code-block:: python242 140-Since the view class itself is not the view function that is added to the141-routing system it does not make much sense to decorate the class itself.142-Instead you either have to decorate the return value of143-:meth:`~flask.views.View.as_view` by hand::243+ from flask.views import MethodView244 145- def user_required(f):146- """Checks whether user is logged in or raises error 401."""147- def decorator(*args, **kwargs):148- if not g.user:149- abort(401)150- return f(*args, **kwargs)151- return decorator245+ class ItemAPI(MethodView):246+ init_every_request = False247 153- view = user_required(UserAPI.as_view('users'))154- app.add_url_rule('/users/', view_func=view)248+ def __init__(self, model):249+ self.model250+ self.validator = generate_validator(model)251 156-Starting with Flask 0.8 there is also an alternative way where you can157-specify a list of decorators to apply in the class declaration::252+ def _get_item(self, id):253+ return self.model.query.get_or_404(id)254 159- class UserAPI(MethodView):160- decorators = [user_required]255+ def get(self, id):256+ user = self._get_item(id)257+ return jsonify(item.to_json())258 162-Due to the implicit self from the caller's perspective you cannot use163-regular view decorators on the individual methods of the view however,164-keep this in mind.259+ def patch(self, id):260+ item = self._get_item(id)261+ errors = self.validator.validate(item, request.json)262 166-Method Views for APIs167----------------------263+ if errors:264+ return jsonify(errors), 400265 169-Web APIs are often working very closely with HTTP verbs so it makes a lot170-of sense to implement such an API based on the171-:class:`~flask.views.MethodView`. That said, you will notice that the API172-will require different URL rules that go to the same method view most of173-the time. For instance consider that you are exposing a user object on174-the web:266+ item.update_from_json(request.json)267+ db.session.commit()268+ return jsonify(item.to_json())269 176-=============== =============== ======================================177-URL Method Description178---------------- --------------- --------------------------------------179-``/users/`` ``GET`` Gives a list of all users180-``/users/`` ``POST`` Creates a new user181-``/users/<id>`` ``GET`` Shows a single user182-``/users/<id>`` ``PUT`` Updates a single user183-``/users/<id>`` ``DELETE`` Deletes a single user184-=============== =============== ======================================270+ def delete(self, id):271+ item = self._get_item(id)272+ db.session.delete(item)273+ db.session.commit()274+ return "", 204275 186-So how would you go about doing that with the187-:class:`~flask.views.MethodView`? The trick is to take advantage of the188-fact that you can provide multiple rules to the same view.276+ class GroupAPI(MethodView):277+ init_every_request = False278 190-Let's assume for the moment the view would look like this::279+ def __init__(self, model):280+ self.model = model281+ self.validator = generate_validator(model, create=True)282 192- class UserAPI(MethodView):283+ def get(self):284+ items = self.model.query.all()285+ return jsonify([item.to_json() for item in items])286 194- def get(self, user_id):195- if user_id is None:196- # return a list of users197- pass198- else:199- # expose a single user200- pass201-287 def post(self):203- # create a new user204- pass288+ errors = self.validator.validate(request.json)289 206- def delete(self, user_id):207- # delete a single user208- pass290+ if errors:291+ return jsonify(errors), 400292 210- def put(self, user_id):211- # update a single user212- pass293+ db.session.add(self.model.from_json(request.json))294+ db.session.commit()295+ return jsonify(item.to_json())296 214-So how do we hook this up with the routing system? By adding two rules215-and explicitly mentioning the methods for each::297+ def register_api(app, model, url):298+ app.add_url_rule(f"/{name}/<int:id>", view_func=ItemAPI(f"{name}-item", model))299+ app.add_url_rule(f"/{name}/", view_func=GroupAPI(f"{name}-group", model))300 217- user_view = UserAPI.as_view('user_api')218- app.add_url_rule('/users/', defaults={'user_id': None},219- view_func=user_view, methods=['GET',])220- app.add_url_rule('/users/', view_func=user_view, methods=['POST',])221- app.add_url_rule('/users/<int:user_id>', view_func=user_view,222- methods=['GET', 'PUT', 'DELETE'])301+ register_api(app, User, "users")302+ register_api(app, Story, "stories")303 224-If you have a lot of APIs that look similar you can refactor that225-registration code::304+This produces the following views, a standard REST API!305 227- def register_api(view, endpoint, url, pk='id', pk_type='int'):228- view_func = view.as_view(endpoint)229- app.add_url_rule(url, defaults={pk: None},230- view_func=view_func, methods=['GET',])231- app.add_url_rule(url, view_func=view_func, methods=['POST',])232- app.add_url_rule(f'{url}<{pk_type}:{pk}>', view_func=view_func,233- methods=['GET', 'PUT', 'DELETE'])234-235- register_api(UserAPI, 'user_api', '/users/', pk='user_id')306+================= ========== ===================307+URL Method Description308+----------------- ---------- -------------------309+``/users/`` ``GET`` List all users310+``/users/`` ``POST`` Create a new user311+``/users/<id>`` ``GET`` Show a single user312+``/users/<id>`` ``PATCH`` Update a user313+``/users/<id>`` ``DELETE`` Delete a user314+``/stories/`` ``GET`` List all stories315+``/stories/`` ``POST`` Create a new story316+``/stories/<id>`` ``GET`` Show a single story317+``/stories/<id>`` ``PATCH`` Update a story318+``/stories/<id>`` ``DELETE`` Delete a story319+================= ========== ===================modified:src/flask/views.py+56 added-44 removed
9 unmodified lines10 )11 12 13 class View:14- """Alternative way to use view functions. A subclass has to implement15- :meth:`dispatch_request` which is called with the view arguments from16- the URL routing system. If :attr:`methods` is provided the methods17- do not have to be passed to the :meth:`~flask.Flask.add_url_rule`18- method explicitly::14+ """Subclass this class and override :meth:`dispatch_request` to15+ create a generic class-based view. Call :meth:`as_view` to create a16+ view function that creates an instance of the class with the given17+ arguments and calls its ``dispatch_request`` method with any URL18+ variables.19 20- class MyView(View):21- methods = ['GET']20+ See :doc:`views` for a detailed guide.21 23- def dispatch_request(self, name):24- return f"Hello {name}!"22+ .. code-block:: python23 26- app.add_url_rule('/hello/<name>', view_func=MyView.as_view('myview'))24+ class Hello(View):25+ init_every_request = False26 28- When you want to decorate a pluggable view you will have to either do that29- when the view function is created (by wrapping the return value of30- :meth:`as_view`) or you can use the :attr:`decorators` attribute::27+ def dispatch_request(self, name):28+ return f"Hello, {name}!"29 32- class SecretView(View):33- methods = ['GET']34- decorators = [superuser_required]30+ app.add_url_rule(31+ "/hello/<name>", view_func=Hello.as_view("hello")32+ )33 36- def dispatch_request(self):37- ...34+ Set :attr:`methods` on the class to change what methods the view35+ accepts.36 39- The decorators stored in the decorators list are applied one after another40- when the view function is created. Note that you can *not* use the class41- based decorators since those would decorate the view class and not the42- generated view function!37+ Set :attr:`decorators` on the class to apply a list of decorators to38+ the generated view function. Decorators applied to the class itself39+ will not be applied to the generated view function!40+41+ Set :attr:`init_every_request` to ``False`` for efficiency, unless42+ you need to store request-global data on ``self``.43 """44 45- #: A list of methods this view can handle.46- methods: t.Optional[t.List[str]] = None45+ #: The methods this view is registered for. Uses the same default46+ #: (``["GET", "HEAD", "OPTIONS"]``) as ``route`` and47+ #: ``add_url_rule`` by default.48+ methods: t.ClassVar[t.Optional[t.List[str]]] = None49 48- #: Setting this disables or force-enables the automatic options handling.49- provide_automatic_options: t.Optional[bool] = None50+ #: Control whether the ``OPTIONS`` method is handled automatically.51+ #: Uses the same default (``True``) as ``route`` and52+ #: ``add_url_rule`` by default.53+ provide_automatic_options: t.ClassVar[t.Optional[bool]] = None54 51- #: The canonical way to decorate class-based views is to decorate the52- #: return value of as_view(). However since this moves parts of the53- #: logic from the class declaration to the place where it's hooked54- #: into the routing system.55+ #: A list of decorators to apply, in order, to the generated view56+ #: function. Remember that ``@decorator`` syntax is applied bottom57+ #: to top, so the first decorator in the list would be the bottom58+ #: decorator.59 #:56- #: You can place one or more decorators in this list and whenever the57- #: view function is created the result is automatically decorated.58- #:60 #: .. versionadded:: 0.860- decorators: t.List[t.Callable] = []61+ decorators: t.ClassVar[t.List[t.Callable]] = []62 63 #: Create a new instance of this view class for every request by64 #: default. If a view subclass sets this to ``False``, the same65 #: instance is used for every request.6 unmodified lines72 #: .. versionadded:: 2.273 init_every_request: t.ClassVar[bool] = True74 75 def dispatch_request(self) -> ft.ResponseReturnValue:75- """Subclasses have to override this method to implement the76- actual view function code. This method is called with all77- the arguments from the URL rule.76+ """The actual view function behavior. Subclasses must override77+ this and return a valid response. Any variables from the URL78+ rule are passed as keyword arguments.79 """80 raise NotImplementedError()81 82 @classmethod76 unmodified lines159 cls.methods = methods160 161 162 class MethodView(View, metaclass=MethodViewType):162- """A class-based view that dispatches request methods to the corresponding163- class methods. For example, if you implement a ``get`` method, it will be164- used to handle ``GET`` requests. ::163+ """Dispatches request methods to the corresponding instance methods.164+ For example, if you implement a ``get`` method, it will be used to165+ handle ``GET`` requests.166 167+ This can be useful for defining a REST API.168+169+ :attr:`methods` is automatically set based on the methods defined on170+ the class.171+172+ See :doc:`views` for a detailed guide.173+174+ .. code-block:: python175+176 class CounterAPI(MethodView):177 def get(self):168- return session.get('counter', 0)178+ return str(session.get("counter", 0))179 180 def post(self):171- session['counter'] = session.get('counter', 0) + 1172- return 'OK'181+ session["counter"] = session.get("counter", 0) + 1182+ return redirect(url_for("counter"))183 174- app.add_url_rule('/counter', view_func=CounterAPI.as_view('counter'))184+ app.add_url_rule(185+ "/counter", view_func=CounterAPI.as_view("counter")186+ )187 """188 189 def dispatch_request(self, **kwargs: t.Any) -> ft.ResponseReturnValue:190 meth = getattr(self, request.method.lower(), None)8 unmodified lines