Skip to content
Myr

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

3 files+61 added−13 removed

modified:src/flask/views.py+40 added-12 removed
57 unmodified lines
58 #:59 #: .. versionadded:: 0.860 decorators: t.List[t.Callable] = []6162 #: 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] = True7374 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 lines
8081 @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.8778 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.9394 The arguments passed to this method are forwarded to the view95 class ``__init__`` method.9697 .. versionchanged:: 2.298 Added the ``init_every_request`` class attribute.99 """100 if cls.init_every_request:10182 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)107108 else:109 self = cls(*class_args, **class_kwargs)110111 def view(**kwargs: t.Any) -> ft.ResponseReturnValue:112 return current_app.ensure_sync(self.dispatch_request)(**kwargs)113114 if cls.decorators:115 view.__name__ = name116 view.__module__ = cls.__module__117 for decorator in cls.decorators:
55 unmodified lines
173174 app.add_url_rule('/counter', view_func=CounterAPI.as_view('counter'))175 """176149 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)179180 # 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)184185 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 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