views.rst
This file
Path
docs/views.rst
319 lines · 9.9 KiB
Last changed by
Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
History of this fileTake it
The walk stopped after 200 commits: lines older than 06495e7 point at it.
Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
lines 1–2why, one step back1Class-based Views2=================Merge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
line 3why, one step back3Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
line 4why, one step back4.. currentmodule:: flask.viewsMerge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
line 5why, one step back5Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
lines 6–7why, one step back6This page introduces using the :class:`View` and :class:`MethodView`7classes to write class-based views.Merge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
line 8why, one step back8Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
lines 9–12why, one step back9A class-based view is a class that acts as a view function. Because it10is a class, different instances of the class can be created with11different arguments, to change the behavior of the view. This is also12known as generic, reusable, or pluggable views.Merge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
line 13why, one step back13Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
lines 14–15why, one step back14An example of where this is useful is defining a class that creates an15API based on the database model it is initialized with.Merge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
line 16why, one step back16Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
lines 17–31why, one step back17For more complex API behavior and customization, look into the various18API extensions for Flask.192021Basic Reusable View22-------------------2324Let's walk through an example converting a view function to a view25class. We start with a view function that queries a list of users then26renders a template to show the list.2728.. code-block:: python2930 @app.route("/users/")31 def user_list():Merge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
line 32why, one step back32 users = User.query.all()Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
line 33why, one step back33 return render_template("users.html", users=users)Merge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
line 34why, one step back34Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
lines 35–38why, one step back35This works for the user model, but let's say you also had more models36that needed list pages. You'd need to write another view function for37each model, even though the only thing that would change is the model38and template name.Merge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
line 39why, one step back39Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
lines 40–42why, one step back40Instead, you can write a :class:`View` subclass that will query a model41and render a template. As the first step, we'll convert the view to a42class without any customization.Merge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
line 43why, one step back43Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
lines 44–45why, one step back44.. code-block:: python45Merge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
lines 46–47why, one step back46 from flask.views import View47Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
line 48why, one step back48 class UserList(View):Merge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
lines 49–50why, one step back49 def dispatch_request(self):50 users = User.query.all()Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
line 51why, one step back51 return render_template("users.html", objects=users)Merge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
line 52why, one step back52Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
line 53why, one step back53 app.add_url_rule("/users/", view_func=UserList.as_view("user_list"))Merge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
line 54why, one step back54Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
lines 55–60why, one step back55The :meth:`View.dispatch_request` method is the equivalent of the view56function. Calling :meth:`View.as_view` method will create a view57function 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`.Merge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
line 61why, one step back61Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
line 62why, one step back62.. note::Merge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
line 63why, one step back63Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
lines 64–65why, one step back64 You can't decorate the class with ``@app.route()`` the way you'd65 do with a basic view function.Merge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
line 66why, one step back66Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
lines 67–71why, one step back67Next, we need to be able to register the same view class for different68models and templates, to make it more useful than the original function.69The class will take two arguments, the model and template, and store70them on ``self``. Then ``dispatch_request`` can reference these instead71of hard-coded values.Merge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
line 72why, one step back72Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
line 73why, one step back73.. code-block:: pythonMerge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
line 74why, one step back74Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
lines 75–78why, one step back75 class ListView(View):76 def __init__(self, model, template):77 self.model = model78 self.template = templateMerge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
lines 79–80why, one step back7980 def dispatch_request(self):Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
lines 81–82why, one step back81 items = self.model.query.all()82 return render_template(self.template, items=items)Merge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
line 83why, one step back83Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
lines 84–87why, one step back84Remember, we create the view function with ``View.as_view()`` instead of85creating the class directly. Any extra arguments passed to ``as_view``86are then passed when creating the class. Now we can register the same87view to handle multiple models.Merge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
line 88why, one step back88Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
line 89why, one step back89.. code-block:: pythonMerge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
line 90why, one step back90Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
lines 91–98why, one step back91 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 )Merge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
lines 99–100why, one step back99100Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
lines 101–148why, one step back101URL Variables102-------------103104Any variables captured by the URL are passed as keyword arguments to the105``dispatch_request`` method, as they would be for a regular view106function.107108.. code-block:: python109110 class DetailView(View):111 def __init__(self, model):112 self.model = model113 self.template = f"{model.__name__.lower()}/detail.html"114115 def dispatch_request(self, id)116 item = self.model.query.get_or_404(id)117 return render_template(self.template, item=item)118119 app.add_url_rule("/users/<int:id>", view_func=DetailView.as_view("user_detail"))120121122View Lifetime and ``self``123--------------------------124125By default, a new instance of the view class is created every time a126request 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,128unlike other forms of global state.129130However, if your view class needs to do a lot of complex initialization,131doing it for every request is unnecessary and can be inefficient. To132avoid this, set :attr:`View.init_every_request` to ``False``, which will133only create one instance of the class and use it for every request. In134this case, writing to ``self`` is not safe. If you need to store data135during the request, use :data:`~flask.g` instead.136137In the ``ListView`` example, nothing writes to ``self`` during the138request, so it is more efficient to create a single instance.139140.. code-block:: python141142 class ListView(View):143 init_every_request = False144145 def __init__(self, model, template):146 self.model = model147 self.template = template148Merge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
line 149why, one step back149 def dispatch_request(self):Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
lines 150–151why, one step back150 items = self.model.query.all()151 return render_template(self.template, items=items)Merge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
line 152why, one step back152Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
lines 153–154why, one step back153Different instances will still be created each for each ``as_view``154call, but not for each request to those views.Merge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
lines 155–156why, one step back155156Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
lines 157–192why, one step back157View Decorators158---------------159160The view class itself is not the view function. View decorators need to161be applied to the view function returned by ``as_view``, not the class162itself. Set :attr:`View.decorators` to a list of decorators to apply.163164.. code-block:: python165166 class UserList(View):167 decorators = [cache(minutes=2), login_required]168169 app.add_url_rule('/users/', view_func=UserList.as_view())170171If you didn't set ``decorators``, you could apply them manually instead.172This is equivalent to:173174.. code-block:: python175176 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)180181Keep in mind that order matters. If you're used to ``@decorator`` style,182this is equivalent to:183184.. code-block:: python185186 @app.route("/users/")187 @login_required188 @cache(minutes=2)189 def user_list():190 ...191192Merge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
lines 193–195why, one step back193Method Hints194------------195Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
lines 196–199why, one step back196A common pattern is to register a view with ``methods=["GET", "POST"]``,197then 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``.Merge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
line 200why, one step back200Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
lines 201–202why, one step back201.. code-block:: python202Merge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
line 203why, one step back203 class MyView(View):Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
line 204why, one step back204 methods = ["GET", "POST"]Merge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
lines 205–206why, one step back205206 def dispatch_request(self):Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
line 207why, one step back207 if request.method == "POST":Merge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
lines 208–210why, one step back208 ...209 ...210Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
line 211why, one step back211 app.add_url_rule('/my-view', view_func=MyView.as_view('my-view'))Merge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
line 212why, one step back212Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
lines 213–214why, one step back213This is equivalent to the following, except further subclasses can214inherit or change the methods.Merge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
line 215why, one step back215Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
line 216why, one step back216.. code-block:: pythonMerge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
line 217why, one step back217Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
lines 218–222why, one step back218 app.add_url_rule(219 "/my-view",220 view_func=MyView.as_view("my-view"),221 methods=["GET", "POST"],222 )Merge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
lines 223–224why, one step back223224Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
lines 225–226why, one step back225Method Dispatching and APIs226---------------------------Merge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
line 227why, one step back227Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
lines 228–231why, one step back228For APIs it can be helpful to use a different function for each HTTP229method. :class:`MethodView` extends the basic :class:`View` to dispatch230to different methods of the class based on the request method. Each HTTP231method maps to a method of the class with the same (lowercase) name.Merge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
line 232why, one step back232Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
lines 233–235why, one step back233:class:`MethodView` automatically sets :attr:`View.methods` based on the234methods defined by the class. It even knows how to handle subclasses235that override or define other methods.Merge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
line 236why, one step back236Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
lines 237–239why, one step back237We can make a generic ``ItemAPI`` class that provides get (detail),238patch (edit), and delete methods for a given model. A ``GroupAPI`` can239provide get (list) and post (create) methods.Merge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
line 240why, one step back240Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
line 241why, one step back241.. code-block:: pythonMerge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
line 242why, one step back242Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
line 243why, one step back243 from flask.views import MethodViewMerge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
line 244why, one step back244Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
lines 245–246why, one step back245 class ItemAPI(MethodView):246 init_every_request = FalseMerge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
line 247why, one step back247Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
lines 248–250why, one step back248 def __init__(self, model):249 self.model250 self.validator = generate_validator(model)Merge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
line 251why, one step back251Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
lines 252–253why, one step back252 def _get_item(self, id):253 return self.model.query.get_or_404(id)Merge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
line 254why, one step back254Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
lines 255–257why, one step back255 def get(self, id):256 user = self._get_item(id)257 return jsonify(item.to_json())Merge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
line 258why, one step back258Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
lines 259–261why, one step back259 def patch(self, id):260 item = self._get_item(id)261 errors = self.validator.validate(item, request.json)Merge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
line 262why, one step back262Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
lines 263–264why, one step back263 if errors:264 return jsonify(errors), 400Merge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
line 265why, one step back265Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
lines 266–268why, one step back266 item.update_from_json(request.json)267 db.session.commit()268 return jsonify(item.to_json())Merge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
line 269why, one step back269Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
lines 270–274why, one step back270 def delete(self, id):271 item = self._get_item(id)272 db.session.delete(item)273 db.session.commit()274 return "", 204Merge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
line 275why, one step back275Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
lines 276–277why, one step back276 class GroupAPI(MethodView):277 init_every_request = FalseMerge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
line 278why, one step back278Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
lines 279–281why, one step back279 def __init__(self, model):280 self.model = model281 self.validator = generate_validator(model, create=True)Merge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
line 282why, one step back282Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
lines 283–285why, one step back283 def get(self):284 items = self.model.query.all()285 return jsonify([item.to_json() for item in items])Merge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
lines 286–287why, one step back286287 def post(self):Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
line 288why, one step back288 errors = self.validator.validate(request.json)Merge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
line 289why, one step back289Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
lines 290–291why, one step back290 if errors:291 return jsonify(errors), 400Merge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
line 292why, one step back292Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
lines 293–295why, one step back293 db.session.add(self.model.from_json(request.json))294 db.session.commit()295 return jsonify(item.to_json())Merge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
line 296why, one step back296Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
lines 297–299why, one step back297 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))Merge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
line 300why, one step back300Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
lines 301–302why, one step back301 register_api(app, User, "users")302 register_api(app, Story, "stories")Merge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
line 303why, one step back303Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
line 304why, one step back304This produces the following views, a standard REST API!Merge pull request #3785 from tirkarthi/add-py39David Lordbefore adoption06495e7
line 305why, one step back305Merge pull request #4624 from pallets/view-init-scopeDavid Lordbefore adoptiondb3187f
lines 306–319why, one step back306================= ========== ===================307URL 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================= ========== ===================