apply setupmethod consistently
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 eb36135 · Browse files · 3 files·+53 added−30 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+53 added−30 removed
- other:+53 added−30 removed
Provenance
- Commit
a406c29- Tree
5dbecf5- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
eb36135
3 files changed+53 added−30 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 TeardownCallable193 unmodified lines207 self.url_values_defaults = url_defaults208 self.cli_group = cli_group209 self._blueprints: t.List[t.Tuple["Blueprint", dict]] = []210 210- def _is_setup_finished(self) -> bool:211- return 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 """219- if self._got_registered_once:220- # TODO: Upgrade this to an error and unify it setupmethod in 2.3221- 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.\n This warning will be become an exception in 2.3."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+8 added-15 removed
35 unmodified lines36 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.0464 unmodified lines