Merge pull request #4577 from hallacy/hallacy/fix_4571
Before adoption: this commit came in with the history the project adopted, so no landing records it.
update setupmethod behavior
authored by David Lord · committed by GitHub · parents ca8e621, e044b00 · Browse files · 5 files·+102 added−83 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+102 added−83 removed
- tests:+42 added−52 removed
- other:+60 added−31 removed
Provenance
- Commit
a52a7db- Tree
f641a5b- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
ca8e621- Parent 2
e044b00
5 files changed+102 added−83 removed
modified:src/flask/app.py+11 added-2 removed
539 unmodified lines540 # Set the name of the Click group in case someone wants to add541 # the app's commands to another CLI tool.542 self.cli.name = self.name543 544- def _is_setup_finished(self) -> bool:545- return self.debug and self._got_first_request544+ def _check_setup_finished(self, f_name: str) -> None:545+ if self._got_first_request:546+ raise AssertionError(547+ f"The setup method '{f_name}' can no longer be called"548+ " on the application. It has already handled its first"549+ " request, any changes will not be applied"550+ " consistently.\n"551+ "Make sure all imports, decorators, functions, etc."552+ " needed to set up the application are done before"553+ " running it."554+ )555 556 @locked_cached_property557 def name(self) -> str: # type: ignore558 """The name of the application. This is usually the import name1729 unmodified linesmodified:src/flask/blueprints.py+34 added-13 removed
4 unmodified lines5 6 from .scaffold import _endpoint_from_view_func7 from .scaffold import _sentinel8 from .scaffold import Scaffold9+from .scaffold import setupmethod10 from .typing import AfterRequestCallable11 from .typing import BeforeFirstRequestCallable12 from .typing import BeforeRequestCallable13 from .typing import TeardownCallable148 unmodified lines162 163 .. versionadded:: 0.7164 """165 165- warn_on_modifications = False166 _got_registered_once = False167 168 #: Blueprint local JSON encoder class to use. Set to ``None`` to use169 #: the app's :class:`~flask.Flask.json_encoder`.37 unmodified lines207 self.url_values_defaults = url_defaults208 self.cli_group = cli_group209 self._blueprints: t.List[t.Tuple["Blueprint", dict]] = []210 211- def _is_setup_finished(self) -> bool:212- return self.warn_on_modifications and self._got_registered_once211+ def _check_setup_finished(self, f_name: str) -> None:212+ if self._got_registered_once:213+ import warnings214 215+ warnings.warn(216+ f"The setup method '{f_name}' can no longer be called on"217+ f" the blueprint '{self.name}'. It has already been"218+ " registered at least once, any changes will not be"219+ " applied consistently.\n"220+ "Make sure all imports, decorators, functions, etc."221+ " needed to set up the blueprint are done before"222+ " registering it.\n"223+ "This warning will become an exception in Flask 2.3.",224+ UserWarning,225+ stacklevel=3,226+ )227+228+ @setupmethod229 def record(self, func: t.Callable) -> None:230 """Registers a function that is called when the blueprint is231 registered on the application. This function is called with the232 state as argument as returned by the :meth:`make_setup_state`233 method.234 """220- if self._got_registered_once and self.warn_on_modifications:221- from warnings import warn222-223- warn(224- Warning(225- "The blueprint was already registered once but is"226- " getting modified now. These changes will not show"227- " up."228- )229- )235 self.deferred_functions.append(func)236 237+ @setupmethod238 def record_once(self, func: t.Callable) -> None:239 """Works like :meth:`record` but wraps the function in another240 function that will ensure the function is only called once. If the241 blueprint is registered a second time on the application, the14 unmodified lines256 Subclasses can override this to return a subclass of the setup state.257 """258 return BlueprintSetupState(self, app, options, first_registration)259 260+ @setupmethod261 def register_blueprint(self, blueprint: "Blueprint", **options: t.Any) -> None:262 """Register a :class:`~flask.Blueprint` on this blueprint. Keyword263 arguments passed to this method will override the defaults set264 on the blueprint.131 unmodified lines396 397 bp_options["name_prefix"] = name398 blueprint.register(app, bp_options)399 400+ @setupmethod401 def add_url_rule(402 self,403 rule: str,404 endpoint: t.Optional[str] = None,19 unmodified lines424 **options,425 )426 )427 428+ @setupmethod429 def app_template_filter(430 self, name: t.Optional[str] = None431 ) -> t.Callable[[TemplateFilterCallable], TemplateFilterCallable]:432 """Register a custom template filter, available application wide. Like8 unmodified lines441 return f442 443 return decorator444 445+ @setupmethod446 def add_app_template_filter(447 self, f: TemplateFilterCallable, name: t.Optional[str] = None448 ) -> None:449 """Register a custom template filter, available application wide. Like8 unmodified lines458 state.app.jinja_env.filters[name or f.__name__] = f459 460 self.record_once(register_template)461 462+ @setupmethod463 def app_template_test(464 self, name: t.Optional[str] = None465 ) -> t.Callable[[TemplateTestCallable], TemplateTestCallable]:466 """Register a custom template test, available application wide. Like10 unmodified lines477 return f478 479 return decorator480 481+ @setupmethod482 def add_app_template_test(483 self, f: TemplateTestCallable, name: t.Optional[str] = None484 ) -> None:485 """Register a custom template test, available application wide. Like10 unmodified lines496 state.app.jinja_env.tests[name or f.__name__] = f497 498 self.record_once(register_template)499 500+ @setupmethod501 def app_template_global(502 self, name: t.Optional[str] = None503 ) -> t.Callable[[TemplateGlobalCallable], TemplateGlobalCallable]:504 """Register a custom template global, available application wide. Like10 unmodified lines515 return f516 517 return decorator518 519+ @setupmethod520 def add_app_template_global(521 self, f: TemplateGlobalCallable, name: t.Optional[str] = None522 ) -> None:523 """Register a custom template global, available application wide. Like10 unmodified lines534 state.app.jinja_env.globals[name or f.__name__] = f535 536 self.record_once(register_template)537 538+ @setupmethod539 def before_app_request(self, f: BeforeRequestCallable) -> BeforeRequestCallable:540 """Like :meth:`Flask.before_request`. Such a function is executed541 before each request, even if outside of a blueprint.542 """1 unmodified line544 lambda s: s.app.before_request_funcs.setdefault(None, []).append(f)545 )546 return f547 548+ @setupmethod549 def before_app_first_request(550 self, f: BeforeFirstRequestCallable551 ) -> BeforeFirstRequestCallable:552 """Like :meth:`Flask.before_first_request`. Such a function is10 unmodified lines563 lambda s: s.app.after_request_funcs.setdefault(None, []).append(f)564 )565 return f566 567+ @setupmethod568 def teardown_app_request(self, f: TeardownCallable) -> TeardownCallable:569 """Like :meth:`Flask.teardown_request` but for a blueprint. Such a570 function is executed when tearing down each request, even if outside of571 the blueprint.2 unmodified lines574 lambda s: s.app.teardown_request_funcs.setdefault(None, []).append(f)575 )576 return f577 578+ @setupmethod579 def app_context_processor(580 self, f: TemplateContextProcessorCallable581 ) -> TemplateContextProcessorCallable:582 """Like :meth:`Flask.context_processor` but for a blueprint. Such a3 unmodified lines586 lambda s: s.app.template_context_processors.setdefault(None, []).append(f)587 )588 return f589 590+ @setupmethod591 def app_errorhandler(self, code: t.Union[t.Type[Exception], int]) -> t.Callable:592 """Like :meth:`Flask.errorhandler` but for a blueprint. This593 handler is used for all requests, even if outside of the blueprint.594 """3 unmodified lines598 return f599 600 return decorator601 602+ @setupmethod603 def app_url_value_preprocessor(604 self, f: URLValuePreprocessorCallable605 ) -> URLValuePreprocessorCallable:606 """Same as :meth:`url_value_preprocessor` but application wide."""1 unmodified line608 lambda s: s.app.url_value_preprocessors.setdefault(None, []).append(f)609 )610 return f611 612+ @setupmethod613 def app_url_defaults(self, f: URLDefaultCallable) -> URLDefaultCallable:614 """Same as :meth:`url_defaults` but application wide."""615 self.record_once(616 lambda s: s.app.url_default_functions.setdefault(None, []).append(f)2 unmodified linesmodified:src/flask/scaffold.py+11 added-16 removed
25 unmodified lines26 from .typing import URLDefaultCallable27 from .typing import URLValuePreprocessorCallable28 29 if t.TYPE_CHECKING: # pragma: no cover30- from .wrappers import Response30 from .typing import ErrorHandlerCallable31+ from .wrappers import Response32 33 # a singleton sentinel value for parameter defaults34 _sentinel = object()35 36 F = t.TypeVar("F", bound=t.Callable[..., t.Any])37 38 39 def setupmethod(f: F) -> F:40- """Wraps a method so that it performs a check in debug mode if the41- first request was already handled.42- """40+ f_name = f.__name__41 42 def wrapper_func(self, *args: t.Any, **kwargs: t.Any) -> t.Any:45- if self._is_setup_finished():46- raise AssertionError(47- "A setup function was called after the first request "48- "was handled. This usually indicates a bug in the"49- " application where a module was not imported and"50- " decorators or other functionality was called too"51- " late.\nTo fix this make sure to import all your view"52- " modules, database models, and everything related at a"53- " central place before the application starts serving"54- " requests."55- )43+ self._check_setup_finished(f_name)44 return f(self, *args, **kwargs)45 46 return t.cast(F, update_wrapper(wrapper_func, f))47 178 unmodified lines226 227 def __repr__(self) -> str:228 return f"<{type(self).__name__} {self.name!r}>"229 242- def _is_setup_finished(self) -> bool:230+ def _check_setup_finished(self, f_name: str) -> None:231 raise NotImplementedError232 233 @property234 def static_folder(self) -> t.Optional[str]:128 unmodified lines363 raise TypeError("Use the 'route' decorator to use the 'methods' argument.")364 365 return self.route(rule, methods=[method], **options)366 367+ @setupmethod368 def get(self, rule: str, **options: t.Any) -> t.Callable[[F], F]:369 """Shortcut for :meth:`route` with ``methods=["GET"]``.370 371 .. versionadded:: 2.0372 """373 return self._method_route("GET", rule, options)374 375+ @setupmethod376 def post(self, rule: str, **options: t.Any) -> t.Callable[[F], F]:377 """Shortcut for :meth:`route` with ``methods=["POST"]``.378 379 .. versionadded:: 2.0380 """381 return self._method_route("POST", rule, options)382 383+ @setupmethod384 def put(self, rule: str, **options: t.Any) -> t.Callable[[F], F]:385 """Shortcut for :meth:`route` with ``methods=["PUT"]``.386 387 .. versionadded:: 2.0388 """389 return self._method_route("PUT", rule, options)390 391+ @setupmethod392 def delete(self, rule: str, **options: t.Any) -> t.Callable[[F], F]:393 """Shortcut for :meth:`route` with ``methods=["DELETE"]``.394 395 .. versionadded:: 2.0396 """397 return self._method_route("DELETE", rule, options)398 399+ @setupmethod400 def patch(self, rule: str, **options: t.Any) -> t.Callable[[F], F]:401 """Shortcut for :meth:`route` with ``methods=["PATCH"]``.402 403 .. versionadded:: 2.0404 """405 return self._method_route("PATCH", rule, options)406 407+ @setupmethod408 def route(self, rule: str, **options: t.Any) -> t.Callable[[F], F]:409 """Decorate a view function to register it with the given URL410 rule and options. Calls :meth:`add_url_rule`, which has more411 details about the implementation.91 unmodified lines503 :class:`~werkzeug.routing.Rule` object.504 """505 raise NotImplementedError506 507+ @setupmethod508 def endpoint(self, endpoint: str) -> t.Callable:509 """Decorate a view function to register it for the given510 endpoint. Used if a rule is added without a ``view_func`` with511 :meth:`add_url_rule`.356 unmodified linesmodified:tests/test_basic.py+42 added-52 removed
327 unmodified lines328 def index():329 flask.session["testing"] = 42330 return "Hello World"331 332+ @app.route("/clear")333+ def clear():334+ flask.session.pop("testing", None)335+ return "Goodbye World"336+337 rv = client.get("/", "http://www.example.com:8080/test/")338 cookie = rv.headers["set-cookie"].lower()339 assert "domain=.example.com" in cookie340 assert "path=/" in cookie341 assert "secure" in cookie342 assert "httponly" not in cookie343 assert "samesite" in cookie344 340- @app.route("/clear")341- def clear():342- flask.session.pop("testing", None)343- return "Goodbye World"344-345 rv = client.get("/clear", "http://www.example.com:8080/test/")346 cookie = rv.headers["set-cookie"].lower()347 assert "session=;" in cookie348 assert "domain=.example.com" in cookie681 unmodified lines1030 rv = client.get("/E3")1031 assert rv.data == b"E2"1032 1033 1034-def test_trapping_of_bad_request_key_errors(app, client):1034+@pytest.mark.parametrize(1035+ ("debug", "trap", "expect_key", "expect_abort"),1036+ [(False, None, True, True), (True, None, False, True), (False, True, False, False)],1037+)1038+def test_trap_bad_request_key_error(app, client, debug, trap, expect_key, expect_abort):1039+ app.config["DEBUG"] = debug1040+ app.config["TRAP_BAD_REQUEST_ERRORS"] = trap1041+1042 @app.route("/key")1043 def fail():1044 flask.request.form["missing_key"]1045 1046 @app.route("/abort")1047 def allow_abort():1048 flask.abort(400)1049 1050+ if expect_key:1043- rv = client.get("/key")1044- assert rv.status_code == 4001045- assert b"missing_key" not in rv.data1046- rv = client.get("/abort")1047- assert rv.status_code == 4001051+ rv = client.get("/key")1052+ assert rv.status_code == 4001053+ assert b"missing_key" not in rv.data1054+ else:1055+ with pytest.raises(KeyError) as exc_info:1056+ client.get("/key")1057 1049- app.debug = True1050- with pytest.raises(KeyError) as e:1051- client.get("/key")1052- assert e.errisinstance(BadRequest)1053- assert "missing_key" in e.value.get_description()1058+ assert exc_info.errisinstance(BadRequest)1059+ assert "missing_key" in exc_info.value.get_description()1054- rv = client.get("/abort")1055- assert rv.status_code == 4001060 1057- app.debug = False1058- app.config["TRAP_BAD_REQUEST_ERRORS"] = True1059- with pytest.raises(KeyError):1060- client.get("/key")1061- with pytest.raises(BadRequest):1062- client.get("/abort")1061+ if expect_abort:1062+ rv = client.get("/abort")1063+ assert rv.status_code == 4001064+ else:1065+ with pytest.raises(BadRequest):1066+ client.get("/abort")1067 1068 1069 def test_trapping_of_all_http_exceptions(app, client):1070 app.config["TRAP_HTTP_EXCEPTIONS"] = True593 unmodified lines1664 rv = client.get("/киртест")1665 assert rv.data == b"Hello World!"1666 1667 1664-def test_debug_mode_complains_after_first_request(app, client):1668+def test_no_setup_after_first_request(app, client):1669 app.debug = True1670 1671 @app.route("/")1672 def index():1 unmodified line1674 1675 assert not app.got_first_request1676 assert client.get("/").data == b"Awesome"1677 1674- with pytest.raises(AssertionError) as e:1678+ with pytest.raises(AssertionError) as exc_info:1679 app.add_url_rule("/foo", endpoint="late")1680 1677- assert "A setup function was called" in str(e.value)1681+ assert "setup method 'add_url_rule'" in str(exc_info.value)1682 1679- app.debug = False1683 1681- @app.route("/foo")1682- def working():1683- return "Meh"1684-1685- assert client.get("/foo").data == b"Meh"1686- assert app.got_first_request1687-1688-1684 def test_before_first_request_functions(app, client):1685 got = []1686 1687 @app.before_first_request26 unmodified lines1714 assert app.got_first_request1715 1716 1717 def test_routing_redirect_debugging(monkeypatch, app, client):1723- @app.route("/foo/", methods=["GET", "POST"])1724- def foo():1725- return "success"1718+ app.config["DEBUG"] = True1719 1727- app.debug = False1728- rv = client.post("/foo", data={}, follow_redirects=True)1720+ @app.route("/user/", methods=["GET", "POST"])1721+ def user():1722+ return flask.request.form["status"]1723+1724+ # default redirect code preserves form data1725+ rv = client.post("/user", data={"status": "success"}, follow_redirects=True)1726 assert rv.data == b"success"1727 1731- app.debug = True1732-1733- with client:1734- rv = client.post("/foo", data={}, follow_redirects=True)1735- assert rv.data == b"success"1736- rv = client.get("/foo", data={}, follow_redirects=True)1737- assert rv.data == b"success"1738-1728+ # 301 and 302 raise error1729 monkeypatch.setattr(RequestRedirect, "code", 301)1730 1741- with client, pytest.raises(AssertionError) as e:1742- client.post("/foo", data={})1731+ with client, pytest.raises(AssertionError) as exc_info:1732+ client.post("/user", data={"status": "error"}, follow_redirects=True)1733 1744- assert "canonical URL 'http://localhost/foo/'" in str(e.value)1734+ assert "canonical URL 'http://localhost/user/'" in str(exc_info.value)1735 1736 1737 def test_route_decorator_custom_endpoint(app, client):1738 app.debug = True281 unmodified linesmodified:CHANGES.rst+4 added
14 unmodified lines15 - ``flask.redirect`` will call ``app.redirect``. :issue:`4569`16 17 - Refactor ``register_error_handler`` to consolidate error checking.18 Rewrite some error messages to be more consistent. :issue:`4559`19+- Use Blueprint decorators and functions intended for setup after20+ registering the blueprint will show a warning. In the next version,21+ this will become an error just like the application setup methods.22+ :issue:`4571`23 24 25 Version 2.1.226 -------------1280 unmodified lines