Skip to content
Myr

improve typing for `app.errorhandler` decorator

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Pascal Corpet · committed by pgjones · parent 5205cd4 · Browse files · 5 files+38 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

5 files+38 added−13 removed

  • other:+38 added−13 removed

5 files+38 added−13 removed

modified:src/flask/app.py+4 added-2 removed
59 unmodified lines
60from .templating import Environment61from .typing import AfterRequestCallable62from .typing import BeforeFirstRequestCallable63from .typing import BeforeRequestCallable64from .typing import ErrorHandlerCallable64from .typing import ResponseReturnValue65from .typing import TeardownCallable66from .typing import TemplateContextProcessorCallable67from .typing import TemplateFilterCallable
8 unmodified lines
76 import typing_extensions as te77 from .blueprints import Blueprint78 from .testing import FlaskClient79 from .testing import FlaskCliRunner80 from .typing import ErrorHandlerCallable8182if sys.version_info >= (3, 8):83 iscoroutinefunction = inspect.iscoroutinefunction84else:
1182 unmodified lines
1267 """1268 self.shell_context_processors.append(f)1269 return f12701271 def _find_error_handler(self, e: Exception) -> t.Optional[ErrorHandlerCallable]:1271 def _find_error_handler(1272 self, e: Exception1273 ) -> t.Optional["ErrorHandlerCallable[Exception]"]:1274 """Return a registered error handler for an exception in this order:1275 blueprint handler for a specific code, app handler for a specific code,1276 blueprint handler for an exception class, app handler for an exception1277 class, or ``None`` if a suitable handler is not found.
816 unmodified lines
modified:src/flask/blueprints.py+4 added-2 removed
6 unmodified lines
7from .scaffold import Scaffold8from .typing import AfterRequestCallable9from .typing import BeforeFirstRequestCallable10from .typing import BeforeRequestCallable11from .typing import ErrorHandlerCallable11from .typing import TeardownCallable12from .typing import TemplateContextProcessorCallable13from .typing import TemplateFilterCallable14from .typing import TemplateGlobalCallable
2 unmodified lines
17from .typing import URLValuePreprocessorCallable1819if t.TYPE_CHECKING:20 from .app import Flask21 from .typing import ErrorHandlerCallable2223DeferredSetupFunction = t.Callable[["BlueprintSetupState"], t.Callable]2425
554 unmodified lines
580 """Like :meth:`Flask.errorhandler` but for a blueprint. This581 handler is used for all requests, even if outside of the blueprint.582 """583584 def decorator(f: ErrorHandlerCallable) -> ErrorHandlerCallable:584 def decorator(585 f: "ErrorHandlerCallable[Exception]",586 ) -> "ErrorHandlerCallable[Exception]":587 self.record_once(lambda s: s.app.errorhandler(code)(f))588 return f589590 return decorator
16 unmodified lines
modified:src/flask/scaffold.py+19 added-8 removed
19 unmodified lines
20from .templating import _default_template_ctx_processor21from .typing import AfterRequestCallable22from .typing import AppOrBlueprintKey23from .typing import BeforeRequestCallable24from .typing import ErrorHandlerCallable24from .typing import GenericException25from .typing import TeardownCallable26from .typing import TemplateContextProcessorCallable27from .typing import URLDefaultCallable28from .typing import URLValuePreprocessorCallable2930if t.TYPE_CHECKING:31 from .wrappers import Response32 from .typing import ErrorHandlerCallable3334# a singleton sentinel value for parameter defaults35_sentinel = object()36
107 unmodified lines
144 #: This data structure is internal. It should not be modified145 #: directly and its format may change at any time.146 self.error_handler_spec: t.Dict[147 AppOrBlueprintKey,147 t.Dict[t.Optional[int], t.Dict[t.Type[Exception], ErrorHandlerCallable]],148 t.Dict[149 t.Optional[int],150 t.Dict[t.Type[Exception], "ErrorHandlerCallable[Exception]"],151 ],152 ] = defaultdict(lambda: defaultdict(dict))153154 #: A data structure of functions to call at the beginning of155 #: each request, in the format ``{scope: [functions]}``. The
490 unmodified lines
646 return f647648 @setupmethod649 def errorhandler(646 self, code_or_exception: t.Union[t.Type[Exception], int]647 ) -> t.Callable[[ErrorHandlerCallable], ErrorHandlerCallable]:650 self, code_or_exception: t.Union[t.Type[GenericException], int]651 ) -> t.Callable[652 ["ErrorHandlerCallable[GenericException]"],653 "ErrorHandlerCallable[GenericException]",654 ]:655 """Register a function to handle errors by code or exception class.656657 A decorator that is used to register a function given an658 error code. Example::
21 unmodified lines
680 :param code_or_exception: the code as integer for the handler, or681 an arbitrary exception682 """683677 def decorator(f: ErrorHandlerCallable) -> ErrorHandlerCallable:684 def decorator(685 f: "ErrorHandlerCallable[GenericException]",686 ) -> "ErrorHandlerCallable[GenericException]":687 self.register_error_handler(code_or_exception, f)688 return f689690 return decorator691692 @setupmethod693 def register_error_handler(694 self,686 code_or_exception: t.Union[t.Type[Exception], int],687 f: ErrorHandlerCallable,695 code_or_exception: t.Union[t.Type[GenericException], int],696 f: "ErrorHandlerCallable[GenericException]",697 ) -> None:698 """Alternative error attach function to the :meth:`errorhandler`699 decorator that is more straightforward to use for non decorator700 usage.
15 unmodified lines
716 " code. Use a subclass of HTTPException with that code"717 " instead."718 )719711 self.error_handler_spec[None][code][exc_class] = f720 self.error_handler_spec[None][code][exc_class] = t.cast(721 "ErrorHandlerCallable[Exception]", f722 )723724 @staticmethod725 def _get_exc_class_and_code(726 exc_class_or_code: t.Union[t.Type[Exception], int]
149 unmodified lines
modified:src/flask/typing.py+10 added-1 removed
31 unmodified lines
32 t.Tuple[ResponseValue, StatusCode, HeadersValue],33 "WSGIApplication",34]3536GenericException = t.TypeVar("GenericException", bound=Exception, contravariant=True)3738AppOrBlueprintKey = t.Optional[str] # The App key is None, whereas blueprints are named39AfterRequestCallable = t.Callable[["Response"], "Response"]40BeforeFirstRequestCallable = t.Callable[[], None]41BeforeRequestCallable = t.Callable[[], t.Optional[ResponseReturnValue]]40ErrorHandlerCallable = t.Callable[[Exception], ResponseReturnValue]42TeardownCallable = t.Callable[[t.Optional[BaseException]], None]43TemplateContextProcessorCallable = t.Callable[[], t.Dict[str, t.Any]]44TemplateFilterCallable = t.Callable[..., t.Any]45TemplateGlobalCallable = t.Callable[..., t.Any]46TemplateTestCallable = t.Callable[..., bool]47URLDefaultCallable = t.Callable[[str, dict], None]48URLValuePreprocessorCallable = t.Callable[[t.Optional[str], t.Optional[dict]], None]495051if t.TYPE_CHECKING:52 import typing_extensions as te5354 class ErrorHandlerCallable(te.Protocol[GenericException]):55 def __call__(self, error: GenericException) -> ResponseReturnValue:56 ...
modified:CHANGES.rst+1 added
9 unmodified lines
10 decorators. :issue:`4104`11- Fixed the issue where typing requires template global12 decorators to accept functions with no arguments. :issue:`4098`13- Support View and MethodView instances with async handlers. :issue:`4112`14- Enhance typing of ``app.errorhandler`` decorator. :issue:`4095`151617Version 2.0.118-------------
1154 unmodified lines