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
Provenance
- Commit
cb7cd1e- Tree
2c5e5d4- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
0ef1e65- Parent 2
190dd4d
6 files changed+34 added−36 removed
modified:src/flask/app.py+10 added-8 removed
1263 unmodified lines1264 """1265 self.shell_context_processors.append(f)1266 return f1267 1268- 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 lines1671 len_rv = len(rv)1672 1673 # 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 lines1700 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 lines1732 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 = status1739 1740 # extend existing headers with provided headers1741 if headers:1740- rv.headers.update(headers)1742+ rv.headers.update(headers) # type: ignore[arg-type]1743 1744 return rv1745 1746 def create_url_adapter(340 unmodified linesmodified:src/flask/blueprints.py+1 added-3 removed
572 unmodified lines573 """Like :meth:`Flask.errorhandler` but for a blueprint. This574 handler is used for all requests, even if outside of the blueprint.575 """576 577- 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 f580 581 return decorator16 unmodified linesmodified:src/flask/helpers.py+1 added-1 removed
184 unmodified lines185 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: ignore190 191 192 def url_for(endpoint: str, **values: t.Any) -> str:193 """Generates a URL to the given endpoint with the method provided.597 unmodified linesmodified:src/flask/scaffold.py+7 added-18 removed
19 unmodified lines20 from .templating import _default_template_ctx_processor21 from .typing import AfterRequestCallable22 from .typing import AppOrBlueprintKey23 from .typing import BeforeRequestCallable24-from .typing import GenericException24 from .typing import TeardownCallable25 from .typing import TemplateContextProcessorCallable26 from .typing import URLDefaultCallable27 from .typing import URLValuePreprocessorCallable115 unmodified lines143 #: 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))149 150 #: A data structure of functions to call at the beginning of151 #: each request, in the format ``{scope: [functions]}``. The495 unmodified lines647 return f648 649 @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.654 655 A decorator that is used to register a function given an656 error code. Example::21 unmodified lines678 :param code_or_exception: the code as integer for the handler, or679 an arbitrary exception680 """681 689- 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 f685 686 return decorator687 688 @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 lines712 " code. Use a subclass of HTTPException with that code"713 " instead."714 ) from None715 725- self.error_handler_spec[None][code][exc_class] = t.cast(726- "ErrorHandlerCallable[Exception]", f727- )716+ self.error_handler_spec[None][code][exc_class] = f717 718 @staticmethod719 def _get_exc_class_and_code(720 exc_class_or_code: t.Union[t.Type[Exception], int]149 unmodified linesmodified:src/flask/typing.py+12 added-6 removed
2 unmodified lines3 4 if 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: F4018 9 # The possible types that are directly convertible or are a Response object.10 ResponseValue = 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 ]18 StatusCode = int19 20 # the possible types for an individual HTTP header13 unmodified lines34 t.Tuple[ResponseValue, StatusCode, HeadersValue],35 "WSGIApplication",36 ]37 36-GenericException = t.TypeVar("GenericException", bound=Exception, contravariant=True)37-38 AppOrBlueprintKey = t.Optional[str] # The App key is None, whereas blueprints are named39 AfterRequestCallable = t.Callable[["Response"], "Response"]40 BeforeFirstRequestCallable = t.Callable[[], None]41 BeforeRequestCallable = t.Callable[[], t.Optional[ResponseReturnValue]]3 unmodified lines45 TemplateGlobalCallable = t.Callable[..., t.Any]46 TemplateTestCallable = t.Callable[..., bool]47 URLDefaultCallable = t.Callable[[str, dict], None]48 URLValuePreprocessorCallable = 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/429749-ErrorHandlerCallable = t.Callable[[GenericException], ResponseReturnValue]55+ErrorHandlerCallable = t.Callable[[t.Any], ResponseReturnValue]modified:CHANGES.rst+3 added
45 unmodified lines46 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`53 54 55 Version 2.0.356 -------------1199 unmodified lines