Skip to content
Myr

Merge pull request #4487 from pallets/typing-errorhandler

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

relax `errorhandler` function arg type

authored by David Lord · committed by GitHub · parents 0ef1e65, 190dd4d · Browse files · 6 files+34 added−36 removed
This commit

State

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

Diff stats

6 files+34 added−36 removed

  • other:+34 added−36 removed

6 files+34 added−36 removed

modified:src/flask/app.py+10 added-8 removed
1263 unmodified lines
1264 """1265 self.shell_context_processors.append(f)1266 return f12671268 def _find_error_handler(1269 self, e: Exception1270 ) -> t.Optional["ErrorHandlerCallable[Exception]"]:1268 def _find_error_handler(self, e: Exception) -> t.Optional["ErrorHandlerCallable"]:1269 """Return a registered error handler for an exception in this order:1270 blueprint handler for a specific code, app handler for a specific code,1271 blueprint handler for an exception class, app handler for an exception1272 class, or ``None`` if a suitable handler is not found.
398 unmodified lines
1671 len_rv = len(rv)16721673 # a 3-tuple is unpacked directly1674 if len_rv == 3:1677 rv, status, headers = rv1675 rv, status, headers = rv # type: ignore[misc]1676 # decide if a 2-tuple has status or headers1677 elif len_rv == 2:1678 if isinstance(rv[1], (Headers, dict, tuple, list)):1679 rv, headers = rv1680 else:1683 rv, status = rv1681 rv, status = rv # type: ignore[misc]1682 # other sized tuples are not allowed1683 else:1684 raise TypeError(1685 "The view function did not return a valid response tuple."
14 unmodified lines
1700 if isinstance(rv, (str, bytes, bytearray)):1701 # let the response class set the status and headers instead of1702 # waiting to do it manually, so that the class can handle any1703 # special logic1706 rv = self.response_class(rv, status=status, headers=headers)1704 rv = self.response_class(1705 rv,1706 status=status,1707 headers=headers, # type: ignore[arg-type]1708 )1709 status = headers = None1710 elif isinstance(rv, dict):1711 rv = jsonify(rv)1712 elif isinstance(rv, BaseResponse) or callable(rv):
19 unmodified lines
1732 rv = t.cast(Response, rv)1733 # prefer the status if it was provided1734 if status is not None:1735 if isinstance(status, (str, bytes, bytearray)):1734 rv.status = status # type: ignore1736 rv.status = status1737 else:1738 rv.status_code = status17391740 # extend existing headers with provided headers1741 if headers:1740 rv.headers.update(headers)1742 rv.headers.update(headers) # type: ignore[arg-type]17431744 return rv17451746 def create_url_adapter(
340 unmodified lines
modified:src/flask/blueprints.py+1 added-3 removed
572 unmodified lines
573 """Like :meth:`Flask.errorhandler` but for a blueprint. This574 handler is used for all requests, even if outside of the blueprint.575 """576577 def decorator(578 f: "ErrorHandlerCallable[Exception]",579 ) -> "ErrorHandlerCallable[Exception]":577 def decorator(f: "ErrorHandlerCallable") -> "ErrorHandlerCallable":578 self.record_once(lambda s: s.app.errorhandler(code)(f))579 return f580581 return decorator
16 unmodified lines
modified:src/flask/helpers.py+1 added-1 removed
184 unmodified lines
185 if not args:186 return current_app.response_class()187 if len(args) == 1:188 args = args[0]189 return current_app.make_response(args)189 return current_app.make_response(args) # type: ignore190191192def url_for(endpoint: str, **values: t.Any) -> str:193 """Generates a URL to the given endpoint with the method provided.
597 unmodified lines
modified:src/flask/scaffold.py+7 added-18 removed
19 unmodified lines
20from .templating import _default_template_ctx_processor21from .typing import AfterRequestCallable22from .typing import AppOrBlueprintKey23from .typing import BeforeRequestCallable24from .typing import GenericException24from .typing import TeardownCallable25from .typing import TemplateContextProcessorCallable26from .typing import URLDefaultCallable27from .typing import URLValuePreprocessorCallable
115 unmodified lines
143 #: This data structure is internal. It should not be modified144 #: directly and its format may change at any time.145 self.error_handler_spec: t.Dict[146 AppOrBlueprintKey,148 t.Dict[149 t.Optional[int],150 t.Dict[t.Type[Exception], "ErrorHandlerCallable[Exception]"],151 ],147 t.Dict[t.Optional[int], t.Dict[t.Type[Exception], "ErrorHandlerCallable"]],148 ] = defaultdict(lambda: defaultdict(dict))149150 #: A data structure of functions to call at the beginning of151 #: each request, in the format ``{scope: [functions]}``. The
495 unmodified lines
647 return f648649 @setupmethod650 def errorhandler(655 self, code_or_exception: t.Union[t.Type[GenericException], int]656 ) -> t.Callable[657 ["ErrorHandlerCallable[GenericException]"],658 "ErrorHandlerCallable[GenericException]",659 ]:651 self, code_or_exception: t.Union[t.Type[Exception], int]652 ) -> t.Callable[["ErrorHandlerCallable"], "ErrorHandlerCallable"]:653 """Register a function to handle errors by code or exception class.654655 A decorator that is used to register a function given an656 error code. Example::
21 unmodified lines
678 :param code_or_exception: the code as integer for the handler, or679 an arbitrary exception680 """681689 def decorator(690 f: "ErrorHandlerCallable[GenericException]",691 ) -> "ErrorHandlerCallable[GenericException]":682 def decorator(f: "ErrorHandlerCallable") -> "ErrorHandlerCallable":683 self.register_error_handler(code_or_exception, f)684 return f685686 return decorator687688 @setupmethod689 def register_error_handler(690 self,700 code_or_exception: t.Union[t.Type[GenericException], int],701 f: "ErrorHandlerCallable[GenericException]",691 code_or_exception: t.Union[t.Type[Exception], int],692 f: "ErrorHandlerCallable",693 ) -> None:694 """Alternative error attach function to the :meth:`errorhandler`695 decorator that is more straightforward to use for non decorator696 usage.
15 unmodified lines
712 " code. Use a subclass of HTTPException with that code"713 " instead."714 ) from None715725 self.error_handler_spec[None][code][exc_class] = t.cast(726 "ErrorHandlerCallable[Exception]", f727 )716 self.error_handler_spec[None][code][exc_class] = f717718 @staticmethod719 def _get_exc_class_and_code(720 exc_class_or_code: t.Union[t.Type[Exception], int]
149 unmodified lines
modified:src/flask/typing.py+12 added-6 removed
2 unmodified lines
34if t.TYPE_CHECKING:5 from _typeshed.wsgi import WSGIApplication # noqa: F4016 from werkzeug.datastructures import Headers # noqa: F4017 from .wrappers import Response # noqa: F4017 from werkzeug.wrappers.response import Response # noqa: F40189# The possible types that are directly convertible or are a Response object.10ResponseValue = t.Union[11 "Response",12 t.AnyStr,12 str,13 bytes,14 t.Dict[str, t.Any], # any jsonify-able dict14 t.Generator[t.AnyStr, None, None],15 t.Iterator[str],16 t.Iterator[bytes],17]18StatusCode = int1920# the possible types for an individual HTTP header
13 unmodified lines
34 t.Tuple[ResponseValue, StatusCode, HeadersValue],35 "WSGIApplication",36]3736GenericException = 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]]
3 unmodified lines
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]49# This should take Exception, but that either breaks typing the argument50# with a specific exception, or decorating multiple times with different51# exceptions (and using a union type on the argument).52# https://github.com/pallets/flask/issues/409553# https://github.com/pallets/flask/issues/429554# https://github.com/pallets/flask/issues/429749ErrorHandlerCallable = t.Callable[[GenericException], ResponseReturnValue]55ErrorHandlerCallable = t.Callable[[t.Any], ResponseReturnValue]
modified:CHANGES.rst+3 added
45 unmodified lines
46 context from the ``flask run`` command remains available in the47 loader thread. :issue:`4460`48- Deleting the session cookie uses the ``httponly`` flag.49 :issue:`4485`50- Relax typing for ``errorhandler`` to allow the user to use more51 precise types and decorate the same function multiple times.52 :issue:`4095, 4295, 4297`535455Version 2.0.356-------------
1199 unmodified lines