add View.init_every_request attribute
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 aab1d99 · Browse files · 3 files·+61 added−13 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+61 added−13 removed
- tests:+18 added−0 removed
- other:+43 added−13 removed
Provenance
- Commit
6e23239- Tree
87171d4- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
aab1d99
3 files changed+61 added−13 removed
modified:src/flask/views.py+40 added-12 removed
57 unmodified lines58 #:59 #: .. versionadded:: 0.860 decorators: t.List[t.Callable] = []61 62+ #: Create a new instance of this view class for every request by63+ #: default. If a view subclass sets this to ``False``, the same64+ #: instance is used for every request.65+ #:66+ #: A single instance is more efficient, especially if complex setup67+ #: is done during init. However, storing data on ``self`` is no68+ #: longer safe across requests, and :data:`~flask.g` should be used69+ #: instead.70+ #:71+ #: .. versionadded:: 2.272+ init_every_request: t.ClassVar[bool] = True73+74 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.2 unmodified lines80 81 @classmethod82 def as_view(83 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.84+ ) -> ft.ViewCallable:85+ """Convert the class into a view function that can be registered86+ for a route.87 78- The arguments passed to :meth:`as_view` are forwarded to the79- constructor of the class.88+ By default, the generated view will create a new instance of the89+ view class for every request and call its90+ :meth:`dispatch_request` method. If the view class sets91+ :attr:`init_every_request` to ``False``, the same instance will92+ be used for every request.93+94+ The arguments passed to this method are forwarded to the view95+ class ``__init__`` method.96+97+ .. versionchanged:: 2.298+ Added the ``init_every_request`` class attribute.99 """100+ if cls.init_every_request:101 82- 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)102+ def view(**kwargs: t.Any) -> ft.ResponseReturnValue:103+ self = view.view_class( # type: ignore[attr-defined]104+ *class_args, **class_kwargs105+ )106+ return current_app.ensure_sync(self.dispatch_request)(**kwargs)107 108+ else:109+ self = cls(*class_args, **class_kwargs)110+111+ def view(**kwargs: t.Any) -> ft.ResponseReturnValue:112+ return current_app.ensure_sync(self.dispatch_request)(**kwargs)113+114 if cls.decorators:115 view.__name__ = name116 view.__module__ = cls.__module__117 for decorator in cls.decorators:55 unmodified lines173 174 app.add_url_rule('/counter', view_func=CounterAPI.as_view('counter'))175 """176 149- def dispatch_request(self, *args: t.Any, **kwargs: t.Any) -> ft.ResponseReturnValue:177+ def dispatch_request(self, **kwargs: t.Any) -> ft.ResponseReturnValue:178 meth = getattr(self, request.method.lower(), None)179 180 # If the request method is HEAD and we don't have a handler for it181 # retry with GET.182 if meth is None and request.method == "HEAD":183 meth = getattr(self, "get", None)184 185 assert meth is not None, f"Unimplemented method {request.method!r}"158- return current_app.ensure_sync(meth)(*args, **kwargs)186+ return current_app.ensure_sync(meth)(**kwargs)modified:tests/test_views.py+18 added
238 unmodified lines239 240 assert client.get("/").data == b"GET"241 assert client.post("/").status_code == 405242 assert sorted(View.methods) == ["GET"]243+244+245+def test_init_once(app, client):246+ n = 0247+248+ class CountInit(flask.views.View):249+ init_every_request = False250+251+ def __init__(self):252+ nonlocal n253+ n += 1254+255+ def dispatch_request(self):256+ return str(n)257+258+ 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 lines21 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`.28 26-29 Version 2.1.330 -------------31 32 Unreleased1289 unmodified lines