Skip to content
Myr

Merge pull request #4624 from pallets/view-init-scope

Before adoption: this commit came in with the history the project adopted, so no landing records it.

add `View.init_every_request` attribute

authored by David Lord · committed by GitHub · parents aab1d99, 45174bf · Browse files · 4 files+378 added−244 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+378 added−244 removed

  • tests:+18 added−0 removed
  • other:+360 added−244 removed

4 files+378 added−244 removed

modified:docs/views.rst+249 added-165 removed
1Pluggable Views2===============1Class-based Views2=================34.. versionadded:: 0.74.. currentmodule:: flask.views56Flask 0.7 introduces pluggable views inspired by the generic views from7Django which are based on classes instead of functions. The main8intention is that you can replace parts of the implementations and this9way have customizable pluggable views.6This page introduces using the :class:`View` and :class:`MethodView`7classes to write class-based views.811Basic Principle12---------------9A 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.1314Consider you have a function that loads a list of objects from the15database and renders into a template::14An example of where this is useful is defining a class that creates an15API based on the database model it is initialized with.1617 @app.route('/users/')18 def show_users(page):17For 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():32 users = User.query.all()20 return render_template('users.html', users=users)33 return render_template("users.html", users=users)3422This is simple and flexible, but if you want to provide this view in a23generic fashion that can be adapted to other models and templates as well24you might want more flexibility. This is where pluggable class-based25views come into place. As the first step to convert this into a class26based view you would do this::35This 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.3940Instead, 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.4344.. code-block:: python4546 from flask.views import View4731 class ShowUsers(View):3248 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)5237 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"))5439As 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 that42class into an actual view function by using the43:meth:`~flask.views.View.as_view` class method. The string you pass to44that function is the name of the endpoint that view will then have. But45this by itself is not helpful, so let's refactor the code a bit::55The :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`.6162.. note::6348 from flask.views import View64 You can't decorate the class with ``@app.route()`` the way you'd65 do with a basic view function.6650 class ListView(View):67Next, 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.7252 def get_template_name(self):53 raise NotImplementedError()73.. code-block:: python7455 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 = template7980 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)8362 class UserView(ListView):84Remember, 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.8864 def get_template_name(self):65 return 'users.html'89.. code-block:: python9067 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 )9970This of course is not that helpful for such a small example, but it's good71enough to explain the basic principle. When you have a class-based view72the question comes up what ``self`` points to. The way this works is that73whenever the request is dispatched a new instance of the class is created74and the :meth:`~flask.views.View.dispatch_request` method is called with75the parameters from the URL rule. The class itself is instantiated with76the parameters passed to the :meth:`~flask.views.View.as_view` function.77For instance you can write a class like this::10079 class RenderTemplateView(View):80 def __init__(self, template_name):81 self.template_name = template_name101URL 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 = template148149 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)15285And then you can register it like this::153Different instances will still be created each for each ``as_view``154call, but not for each request to those views.15587 app.add_url_rule('/about', view_func=RenderTemplateView.as_view(88 'about_page', template_name='about.html'))156157View 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 ...191192193Method Hints194------------19593Pluggable views are attached to the application like a regular function by94either using :func:`~flask.Flask.route` or better95:meth:`~flask.Flask.add_url_rule`. That however also means that you would96have to provide the names of the HTTP methods the view supports when you97attach this. In order to move that information to the class you can98provide a :attr:`~flask.views.View.methods` attribute that has this99information::196A 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``.200201.. code-block:: python202203 class MyView(View):102 methods = ['GET', 'POST']204 methods = ["GET", "POST"]205206 def dispatch_request(self):105 if request.method == 'POST':207 if request.method == "POST":208 ...209 ...210109 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'))212111Method Based Dispatching112------------------------213This is equivalent to the following, except further subclasses can214inherit or change the methods.215114For RESTful APIs it's especially helpful to execute a different function115for each HTTP method. With the :class:`flask.views.MethodView` you can116easily do that. Each HTTP method maps to a method of the class with the117same name (just in lowercase)::216.. code-block:: python217119 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 )223121 class UserAPI(MethodView):224123 def get(self):124 users = User.query.all()125 ...225Method Dispatching and APIs226---------------------------227127 def post(self):128 user = User.from_form_data(request.form)129 ...228For 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.232131 app.add_url_rule('/users/', view_func=UserAPI.as_view('users'))233: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.236133That way you also don't have to provide the134:attr:`~flask.views.View.methods` attribute. It's automatically set based135on the methods defined in the class.237We 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.240137Decorating Views138----------------241.. code-block:: python242140Since the view class itself is not the view function that is added to the141routing system it does not make much sense to decorate the class itself.142Instead you either have to decorate the return value of143:meth:`~flask.views.View.as_view` by hand::243 from flask.views import MethodView244145 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 = False247153 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)251156Starting with Flask 0.8 there is also an alternative way where you can157specify 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)254159 class UserAPI(MethodView):160 decorators = [user_required]255 def get(self, id):256 user = self._get_item(id)257 return jsonify(item.to_json())258162Due to the implicit self from the caller's perspective you cannot use163regular view decorators on the individual methods of the view however,164keep this in mind.259 def patch(self, id):260 item = self._get_item(id)261 errors = self.validator.validate(item, request.json)262166Method Views for APIs167---------------------263 if errors:264 return jsonify(errors), 400265169Web APIs are often working very closely with HTTP verbs so it makes a lot170of sense to implement such an API based on the171:class:`~flask.views.MethodView`. That said, you will notice that the API172will require different URL rules that go to the same method view most of173the time. For instance consider that you are exposing a user object on174the web:266 item.update_from_json(request.json)267 db.session.commit()268 return jsonify(item.to_json())269176=============== =============== ======================================177URL 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 "", 204275186So how would you go about doing that with the187:class:`~flask.views.MethodView`? The trick is to take advantage of the188fact that you can provide multiple rules to the same view.276 class GroupAPI(MethodView):277 init_every_request = False278190Let'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)282192 class UserAPI(MethodView):283 def get(self):284 items = self.model.query.all()285 return jsonify([item.to_json() for item in items])286194 def get(self, user_id):195 if user_id is None:196 # return a list of users197 pass198 else:199 # expose a single user200 pass201287 def post(self):203 # create a new user204 pass288 errors = self.validator.validate(request.json)289206 def delete(self, user_id):207 # delete a single user208 pass290 if errors:291 return jsonify(errors), 400292210 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())296214So how do we hook this up with the routing system? By adding two rules215and 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))300217 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")303224If you have a lot of APIs that look similar you can refactor that225registration code::304This produces the following views, a standard REST API!305227 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'])234235 register_api(UserAPI, 'user_api', '/users/', pk='user_id')306================= ========== ===================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================= ========== ===================
modified:src/flask/views.py+108 added-78 removed
9 unmodified lines
10)111213class 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.1920 class MyView(View):21 methods = ['GET']20 See :doc:`views` for a detailed guide.2123 def dispatch_request(self, name):24 return f"Hello {name}!"22 .. code-block:: python2326 app.add_url_rule('/hello/<name>', view_func=MyView.as_view('myview'))24 class Hello(View):25 init_every_request = False2628 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}!"2932 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 )3336 def dispatch_request(self):37 ...34 Set :attr:`methods` on the class to change what methods the view35 accepts.3639 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!4041 Set :attr:`init_every_request` to ``False`` for efficiency, unless42 you need to store request-global data on ``self``.43 """4445 #: 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.Collection[str]]] = None4948 #: 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]] = None5451 #: 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]] = []6263 #: 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.66 #:67 #: A single instance is more efficient, especially if complex setup68 #: is done during init. However, storing data on ``self`` is no69 #: longer safe across requests, and :data:`~flask.g` should be used70 #: instead.71 #:72 #: .. versionadded:: 2.273 init_every_request: t.ClassVar[bool] = True7475 def dispatch_request(self) -> ft.ResponseReturnValue:63 """Subclasses have to override this method to implement the64 actual view function code. This method is called with all65 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()8182 @classmethod83 def as_view(84 cls, name: str, *class_args: t.Any, **class_kwargs: t.Any72 ) -> t.Callable:73 """Converts the class into an actual view function that can be used74 with the routing system. Internally this generates a function on the75 fly which will instantiate the :class:`View` on each request and call76 the :meth:`dispatch_request` method on it.85 ) -> ft.ViewCallable:86 """Convert the class into a view function that can be registered87 for a route.8878 The arguments passed to :meth:`as_view` are forwarded to the79 constructor of the class.89 By default, the generated view will create a new instance of the90 view class for every request and call its91 :meth:`dispatch_request` method. If the view class sets92 :attr:`init_every_request` to ``False``, the same instance will93 be used for every request.9495 The arguments passed to this method are forwarded to the view96 class ``__init__`` method.9798 .. versionchanged:: 2.299 Added the ``init_every_request`` class attribute.100 """101 if cls.init_every_request:10282 def view(*args: t.Any, **kwargs: t.Any) -> ft.ResponseReturnValue:83 self = view.view_class(*class_args, **class_kwargs) # type: ignore84 return current_app.ensure_sync(self.dispatch_request)(*args, **kwargs)103 def view(**kwargs: t.Any) -> ft.ResponseReturnValue:104 self = view.view_class( # type: ignore[attr-defined]105 *class_args, **class_kwargs106 )107 return current_app.ensure_sync(self.dispatch_request)(**kwargs)108109 else:110 self = cls(*class_args, **class_kwargs)111112 def view(**kwargs: t.Any) -> ft.ResponseReturnValue:113 return current_app.ensure_sync(self.dispatch_request)(**kwargs)114115 if cls.decorators:116 view.__name__ = name117 view.__module__ = cls.__module__118 for decorator in cls.decorators:
12 unmodified lines
131 view.provide_automatic_options = cls.provide_automatic_options # type: ignore132 return view133134106class MethodViewType(type):107 """Metaclass for :class:`MethodView` that determines what methods the view108 defines.135class MethodView(View):136 """Dispatches request methods to the corresponding instance methods.137 For example, if you implement a ``get`` method, it will be used to138 handle ``GET`` requests.139140 This can be useful for defining a REST API.141142 :attr:`methods` is automatically set based on the methods defined on143 the class.144145 See :doc:`views` for a detailed guide.146147 .. code-block:: python148149 class CounterAPI(MethodView):150 def get(self):151 return str(session.get("counter", 0))152153 def post(self):154 session["counter"] = session.get("counter", 0) + 1155 return redirect(url_for("counter"))156157 app.add_url_rule(158 "/counter", view_func=CounterAPI.as_view("counter")159 )160 """161111 def __init__(cls, name, bases, d):112 super().__init__(name, bases, d)162 def __init_subclass__(cls, **kwargs: t.Any) -> None:163 super().__init_subclass__(**kwargs)164114 if "methods" not in d:165 if "methods" not in cls.__dict__:166 methods = set()167117 for base in bases:168 for base in cls.__bases__:169 if getattr(base, "methods", None):119 methods.update(base.methods)170 methods.update(base.methods) # type: ignore[attr-defined]171172 for key in http_method_funcs:173 if hasattr(cls, key):174 methods.add(key.upper())175125 # If we have no method at all in there we don't want to add a126 # method list. This is for instance the case for the base class127 # or another subclass of a base method view that does not introduce128 # new methods.176 if methods:177 cls.methods = methods178132133class MethodView(View, metaclass=MethodViewType):134 """A class-based view that dispatches request methods to the corresponding135 class methods. For example, if you implement a ``get`` method, it will be136 used to handle ``GET`` requests. ::137138 class CounterAPI(MethodView):139 def get(self):140 return session.get('counter', 0)141142 def post(self):143 session['counter'] = session.get('counter', 0) + 1144 return 'OK'145146 app.add_url_rule('/counter', view_func=CounterAPI.as_view('counter'))147 """148149 def dispatch_request(self, *args: t.Any, **kwargs: t.Any) -> ft.ResponseReturnValue:179 def dispatch_request(self, **kwargs: t.Any) -> ft.ResponseReturnValue:180 meth = getattr(self, request.method.lower(), None)181182 # If the request method is HEAD and we don't have a handler for it183 # retry with GET.184 if meth is None and request.method == "HEAD":185 meth = getattr(self, "get", None)186187 assert meth is not None, f"Unimplemented method {request.method!r}"158 return current_app.ensure_sync(meth)(*args, **kwargs)188 return current_app.ensure_sync(meth)(**kwargs)
modified:tests/test_views.py+18 added
238 unmodified lines
239240 assert client.get("/").data == b"GET"241 assert client.post("/").status_code == 405242 assert sorted(View.methods) == ["GET"]243244245def test_init_once(app, client):246 n = 0247248 class CountInit(flask.views.View):249 init_every_request = False250251 def __init__(self):252 nonlocal n253 n += 1254255 def dispatch_request(self):256 return str(n)257258 app.add_url_rule("/", view_func=CountInit.as_view("index"))259 assert client.get("/").data == b"1"260 assert client.get("/").data == b"1"
modified:CHANGES.rst+3 added-1 removed
20 unmodified lines
21 this will become an error just like the application setup methods.22 :issue:`4571`23- ``before_first_request`` is deprecated. Run setup code when creating24 the application instead. :issue:`4605`25- Added the ``View.init_every_request`` class attribute. If a view26 subclass sets this to ``False``, the view will not create a new27 instance on every request. :issue:`2520`.282629Version 2.1.330-------------3132Unreleased
1289 unmodified lines