Skip to content
Myr

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

5 files+102 added−83 removed

modified:src/flask/app.py+11 added-2 removed
539 unmodified lines
540 # 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.name543544 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 )555556 @locked_cached_property557 def name(self) -> str: # type: ignore558 """The name of the application. This is usually the import name
1729 unmodified lines
modified:src/flask/blueprints.py+34 added-13 removed
4 unmodified lines
56from .scaffold import _endpoint_from_view_func7from .scaffold import _sentinel8from .scaffold import Scaffold9from .scaffold import setupmethod10from .typing import AfterRequestCallable11from .typing import BeforeFirstRequestCallable12from .typing import BeforeRequestCallable13from .typing import TeardownCallable
148 unmodified lines
162163 .. versionadded:: 0.7164 """165165 warn_on_modifications = False166 _got_registered_once = False167168 #: Blueprint local JSON encoder class to use. Set to ``None`` to use169 #: the app's :class:`~flask.Flask.json_encoder`.
37 unmodified lines
207 self.url_values_defaults = url_defaults208 self.cli_group = cli_group209 self._blueprints: t.List[t.Tuple["Blueprint", dict]] = []210211 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 warnings214215 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 )227228 @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 warn222223 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)236237 @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, the
14 unmodified lines
256 Subclasses can override this to return a subclass of the setup state.257 """258 return BlueprintSetupState(self, app, options, first_registration)259260 @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 lines
396397 bp_options["name_prefix"] = name398 blueprint.register(app, bp_options)399400 @setupmethod401 def add_url_rule(402 self,403 rule: str,404 endpoint: t.Optional[str] = None,
19 unmodified lines
424 **options,425 )426 )427428 @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. Like
8 unmodified lines
441 return f442443 return decorator444445 @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. Like
8 unmodified lines
458 state.app.jinja_env.filters[name or f.__name__] = f459460 self.record_once(register_template)461462 @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. Like
10 unmodified lines
477 return f478479 return decorator480481 @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. Like
10 unmodified lines
496 state.app.jinja_env.tests[name or f.__name__] = f497498 self.record_once(register_template)499500 @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. Like
10 unmodified lines
515 return f516517 return decorator518519 @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. Like
10 unmodified lines
534 state.app.jinja_env.globals[name or f.__name__] = f535536 self.record_once(register_template)537538 @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 line
544 lambda s: s.app.before_request_funcs.setdefault(None, []).append(f)545 )546 return f547548 @setupmethod549 def before_app_first_request(550 self, f: BeforeFirstRequestCallable551 ) -> BeforeFirstRequestCallable:552 """Like :meth:`Flask.before_first_request`. Such a function is
10 unmodified lines
563 lambda s: s.app.after_request_funcs.setdefault(None, []).append(f)564 )565 return f566567 @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 lines
574 lambda s: s.app.teardown_request_funcs.setdefault(None, []).append(f)575 )576 return f577578 @setupmethod579 def app_context_processor(580 self, f: TemplateContextProcessorCallable581 ) -> TemplateContextProcessorCallable:582 """Like :meth:`Flask.context_processor` but for a blueprint. Such a
3 unmodified lines
586 lambda s: s.app.template_context_processors.setdefault(None, []).append(f)587 )588 return f589590 @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 lines
598 return f599600 return decorator601602 @setupmethod603 def app_url_value_preprocessor(604 self, f: URLValuePreprocessorCallable605 ) -> URLValuePreprocessorCallable:606 """Same as :meth:`url_value_preprocessor` but application wide."""
1 unmodified line
608 lambda s: s.app.url_value_preprocessors.setdefault(None, []).append(f)609 )610 return f611612 @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 lines
modified:src/flask/scaffold.py+11 added-16 removed
25 unmodified lines
26from .typing import URLDefaultCallable27from .typing import URLValuePreprocessorCallable2829if t.TYPE_CHECKING: # pragma: no cover30 from .wrappers import Response30 from .typing import ErrorHandlerCallable31 from .wrappers import Response3233# a singleton sentinel value for parameter defaults34_sentinel = object()3536F = t.TypeVar("F", bound=t.Callable[..., t.Any])373839def 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__4142 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)4546 return t.cast(F, update_wrapper(wrapper_func, f))47
178 unmodified lines
226227 def __repr__(self) -> str:228 return f"<{type(self).__name__} {self.name!r}>"229242 def _is_setup_finished(self) -> bool:230 def _check_setup_finished(self, f_name: str) -> None:231 raise NotImplementedError232233 @property234 def static_folder(self) -> t.Optional[str]:
128 unmodified lines
363 raise TypeError("Use the 'route' decorator to use the 'methods' argument.")364365 return self.route(rule, methods=[method], **options)366367 @setupmethod368 def get(self, rule: str, **options: t.Any) -> t.Callable[[F], F]:369 """Shortcut for :meth:`route` with ``methods=["GET"]``.370371 .. versionadded:: 2.0372 """373 return self._method_route("GET", rule, options)374375 @setupmethod376 def post(self, rule: str, **options: t.Any) -> t.Callable[[F], F]:377 """Shortcut for :meth:`route` with ``methods=["POST"]``.378379 .. versionadded:: 2.0380 """381 return self._method_route("POST", rule, options)382383 @setupmethod384 def put(self, rule: str, **options: t.Any) -> t.Callable[[F], F]:385 """Shortcut for :meth:`route` with ``methods=["PUT"]``.386387 .. versionadded:: 2.0388 """389 return self._method_route("PUT", rule, options)390391 @setupmethod392 def delete(self, rule: str, **options: t.Any) -> t.Callable[[F], F]:393 """Shortcut for :meth:`route` with ``methods=["DELETE"]``.394395 .. versionadded:: 2.0396 """397 return self._method_route("DELETE", rule, options)398399 @setupmethod400 def patch(self, rule: str, **options: t.Any) -> t.Callable[[F], F]:401 """Shortcut for :meth:`route` with ``methods=["PATCH"]``.402403 .. versionadded:: 2.0404 """405 return self._method_route("PATCH", rule, options)406407 @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 lines
503 :class:`~werkzeug.routing.Rule` object.504 """505 raise NotImplementedError506507 @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 lines
modified:tests/test_basic.py+42 added-52 removed
327 unmodified lines
328 def index():329 flask.session["testing"] = 42330 return "Hello World"331332 @app.route("/clear")333 def clear():334 flask.session.pop("testing", None)335 return "Goodbye World"336337 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 cookie344340 @app.route("/clear")341 def clear():342 flask.session.pop("testing", None)343 return "Goodbye World"344345 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 cookie
681 unmodified lines
1030 rv = client.get("/E3")1031 assert rv.data == b"E2"103210331034def 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)1038def 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"] = trap10411042 @app.route("/key")1043 def fail():1044 flask.request.form["missing_key"]10451046 @app.route("/abort")1047 def allow_abort():1048 flask.abort(400)10491050 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")10571049 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 == 40010601057 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")106710681069def test_trapping_of_all_http_exceptions(app, client):1070 app.config["TRAP_HTTP_EXCEPTIONS"] = True
593 unmodified lines
1664 rv = client.get("/киртест")1665 assert rv.data == b"Hello World!"166616671664def test_debug_mode_complains_after_first_request(app, client):1668def test_no_setup_after_first_request(app, client):1669 app.debug = True16701671 @app.route("/")1672 def index():
1 unmodified line
16741675 assert not app.got_first_request1676 assert client.get("/").data == b"Awesome"16771674 with pytest.raises(AssertionError) as e:1678 with pytest.raises(AssertionError) as exc_info:1679 app.add_url_rule("/foo", endpoint="late")16801677 assert "A setup function was called" in str(e.value)1681 assert "setup method 'add_url_rule'" in str(exc_info.value)16821679 app.debug = False16831681 @app.route("/foo")1682 def working():1683 return "Meh"16841685 assert client.get("/foo").data == b"Meh"1686 assert app.got_first_request168716881684def test_before_first_request_functions(app, client):1685 got = []16861687 @app.before_first_request
26 unmodified lines
1714 assert app.got_first_request171517161717def test_routing_redirect_debugging(monkeypatch, app, client):1723 @app.route("/foo/", methods=["GET", "POST"])1724 def foo():1725 return "success"1718 app.config["DEBUG"] = True17191727 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"]17231724 # default redirect code preserves form data1725 rv = client.post("/user", data={"status": "success"}, follow_redirects=True)1726 assert rv.data == b"success"17271731 app.debug = True17321733 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"17381728 # 301 and 302 raise error1729 monkeypatch.setattr(RequestRedirect, "code", 301)17301741 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)17331744 assert "canonical URL 'http://localhost/foo/'" in str(e.value)1734 assert "canonical URL 'http://localhost/user/'" in str(exc_info.value)173517361737def test_route_decorator_custom_endpoint(app, client):1738 app.debug = True
281 unmodified lines
modified:CHANGES.rst+4 added
14 unmodified lines
15 - ``flask.redirect`` will call ``app.redirect``. :issue:`4569`1617- 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`232425Version 2.1.226-------------
1280 unmodified lines