Skip to content
Myr

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

3 files+53 added−30 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
193 unmodified lines
207 self.url_values_defaults = url_defaults208 self.cli_group = cli_group209 self._blueprints: t.List[t.Tuple["Blueprint", dict]] = []210210 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 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 """219 if self._got_registered_once:220 # TODO: Upgrade this to an error and unify it setupmethod in 2.3221 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.\n This warning will be become an exception in 2.3."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+8 added-15 removed
35 unmodified lines
36F = 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.0
464 unmodified lines