Merge pull request #4579 from lecovi/docs/#4574-test-typing
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by GitHub · parents 5e40aa2, 4876675 · Browse files · 7 files·+138 added−31 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+138 added−31 removed
- tests:+95 added−0 removed
- other:+43 added−31 removed
Provenance
- Commit
fb89745- Tree
68d5385- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
5e40aa2- Parent 2
4876675
7 files changed+138 added−31 removed
modified:src/flask/app.py+2 added-2 removed
1031 unmodified lines1032 def add_url_rule(1033 self,1034 rule: str,1035 endpoint: t.Optional[str] = None,1036- view_func: t.Optional[t.Callable] = None,1036+ view_func: t.Optional[ft.ViewCallable] = None,1037 provide_automatic_options: t.Optional[bool] = None,1038 **options: t.Any,1039 ) -> None:1040 if endpoint is None:639 unmodified lines1680 elif len_rv == 2:1681 if isinstance(rv[1], (Headers, dict, tuple, list)):1682 rv, headers = rv1683 else:1684- rv, status = rv # type: ignore[misc]1684+ rv, status = rv # type: ignore[assignment,misc]1685 # other sized tuples are not allowed1686 else:1687 raise TypeError(1688 "The view function did not return a valid response tuple."403 unmodified linesmodified:src/flask/blueprints.py+5 added-3 removed
382 unmodified lines383 def add_url_rule(384 self,385 rule: str,386 endpoint: t.Optional[str] = None,387- view_func: t.Optional[t.Callable] = None,387+ view_func: t.Optional[ft.ViewCallable] = None,388 provide_automatic_options: t.Optional[bool] = None,389 **options: t.Any,390 ) -> None:391 """Like :meth:`Flask.add_url_rule` but for a blueprint. The endpoint for168 unmodified lines560 lambda s: s.app.template_context_processors.setdefault(None, []).append(f)561 )562 return f563 564- def app_errorhandler(self, code: t.Union[t.Type[Exception], int]) -> t.Callable:564+ def app_errorhandler(565+ self, code: t.Union[t.Type[Exception], int]566+ ) -> t.Callable[[ft.ErrorHandlerDecorator], ft.ErrorHandlerDecorator]:567 """Like :meth:`Flask.errorhandler` but for a blueprint. This568 handler is used for all requests, even if outside of the blueprint.569 """570 569- def decorator(f: ft.ErrorHandlerCallable) -> ft.ErrorHandlerCallable:571+ def decorator(f: ft.ErrorHandlerDecorator) -> ft.ErrorHandlerDecorator:572 self.record_once(lambda s: s.app.errorhandler(code)(f))573 return f574 575 return decorator16 unmodified linesmodified:src/flask/scaffold.py+23 added-11 removed
361 unmodified lines362 self,363 method: str,364 rule: str,365 options: dict,366- ) -> t.Callable[[F], F]:366+ ) -> t.Callable[[ft.RouteDecorator], ft.RouteDecorator]:367 if "methods" in options:368 raise TypeError("Use the 'route' decorator to use the 'methods' argument.")369 370 return self.route(rule, methods=[method], **options)371 372- def get(self, rule: str, **options: t.Any) -> t.Callable[[F], F]:372+ def get(373+ self, rule: str, **options: t.Any374+ ) -> t.Callable[[ft.RouteDecorator], ft.RouteDecorator]:375 """Shortcut for :meth:`route` with ``methods=["GET"]``.376 377 .. versionadded:: 2.0378 """379 return self._method_route("GET", rule, options)380 379- def post(self, rule: str, **options: t.Any) -> t.Callable[[F], F]:381+ def post(382+ self, rule: str, **options: t.Any383+ ) -> t.Callable[[ft.RouteDecorator], ft.RouteDecorator]:384 """Shortcut for :meth:`route` with ``methods=["POST"]``.385 386 .. versionadded:: 2.0387 """388 return self._method_route("POST", rule, options)389 386- def put(self, rule: str, **options: t.Any) -> t.Callable[[F], F]:390+ def put(391+ self, rule: str, **options: t.Any392+ ) -> t.Callable[[ft.RouteDecorator], ft.RouteDecorator]:393 """Shortcut for :meth:`route` with ``methods=["PUT"]``.394 395 .. versionadded:: 2.0396 """397 return self._method_route("PUT", rule, options)398 393- def delete(self, rule: str, **options: t.Any) -> t.Callable[[F], F]:399+ def delete(400+ self, rule: str, **options: t.Any401+ ) -> t.Callable[[ft.RouteDecorator], ft.RouteDecorator]:402 """Shortcut for :meth:`route` with ``methods=["DELETE"]``.403 404 .. versionadded:: 2.0405 """406 return self._method_route("DELETE", rule, options)407 400- def patch(self, rule: str, **options: t.Any) -> t.Callable[[F], F]:408+ def patch(409+ self, rule: str, **options: t.Any410+ ) -> t.Callable[[ft.RouteDecorator], ft.RouteDecorator]:411 """Shortcut for :meth:`route` with ``methods=["PATCH"]``.412 413 .. versionadded:: 2.0414 """415 return self._method_route("PATCH", rule, options)416 407- def route(self, rule: str, **options: t.Any) -> t.Callable[[F], F]:417+ def route(418+ self, rule: str, **options: t.Any419+ ) -> t.Callable[[ft.RouteDecorator], ft.RouteDecorator]:420 """Decorate a view function to register it with the given URL421 rule and options. Calls :meth:`add_url_rule`, which has more422 details about the implementation.423 15 unmodified lines439 :param options: Extra options passed to the440 :class:`~werkzeug.routing.Rule` object.441 """442 431- def decorator(f: F) -> F:443+ def decorator(f: ft.RouteDecorator) -> ft.RouteDecorator:444 endpoint = options.pop("endpoint", None)445 self.add_url_rule(rule, endpoint, f, **options)446 return f447 3 unmodified lines451 def add_url_rule(452 self,453 rule: str,454 endpoint: t.Optional[str] = None,443- view_func: t.Optional[t.Callable] = None,455+ view_func: t.Optional[ft.ViewCallable] = None,456 provide_automatic_options: t.Optional[bool] = None,457 **options: t.Any,458 ) -> None:459 """Register a rule for routing incoming requests and building193 unmodified lines653 654 @setupmethod655 def errorhandler(656 self, code_or_exception: t.Union[t.Type[Exception], int]645- ) -> t.Callable[[ft.ErrorHandlerCallable], ft.ErrorHandlerCallable]:657+ ) -> t.Callable[[ft.ErrorHandlerDecorator], ft.ErrorHandlerDecorator]:658 """Register a function to handle errors by code or exception class.659 660 A decorator that is used to register a function given an661 error code. Example::21 unmodified lines683 :param code_or_exception: the code as integer for the handler, or684 an arbitrary exception685 """686 675- def decorator(f: ft.ErrorHandlerCallable) -> ft.ErrorHandlerCallable:687+ def decorator(f: ft.ErrorHandlerDecorator) -> ft.ErrorHandlerDecorator:688 self.register_error_handler(code_or_exception, f)689 return f690 691 return decorator183 unmodified linesmodified:src/flask/typing.py+12 added-14 removed
1 import typing as t2 3-3 if t.TYPE_CHECKING:4 from _typeshed.wsgi import WSGIApplication # noqa: F4015 from werkzeug.datastructures import Headers # noqa: F4016 from werkzeug.wrappers import Response # noqa: F4017 8 # The possible types that are directly convertible or are a Response object.10-ResponseValue = t.Union[11- "Response",12- str,13- bytes,14- t.Dict[str, t.Any], # any jsonify-able dict15- t.Iterator[str],16- t.Iterator[bytes],17-]18-StatusCode = int9+ResponseValue = t.Union["Response", str, bytes, t.Dict[str, t.Any]]10 11 # the possible types for an individual HTTP header21-HeaderName = str12+# This should be a Union, but mypy doesn't pass unless it's a TypeVar.13 HeaderValue = t.Union[str, t.List[str], t.Tuple[str, ...]]14 15 # the possible types for HTTP headers16 HeadersValue = t.Union[26- "Headers", t.Dict[HeaderName, HeaderValue], t.List[t.Tuple[HeaderName, HeaderValue]]17+ "Headers",18+ t.Mapping[str, HeaderValue],19+ t.Sequence[t.Tuple[str, HeaderValue]],20 ]21 22 # The possible types returned by a route function.23 ResponseReturnValue = t.Union[24 ResponseValue,25 t.Tuple[ResponseValue, HeadersValue],33- t.Tuple[ResponseValue, StatusCode],34- t.Tuple[ResponseValue, StatusCode, HeadersValue],26+ t.Tuple[ResponseValue, int],27+ t.Tuple[ResponseValue, int, HeadersValue],28 "WSGIApplication",29 ]30 31 # Allow any subclass of werkzeug.Response, such as the one from Flask,11 unmodified lines43 TemplateGlobalCallable = t.Callable[..., t.Any]44 TemplateTestCallable = t.Callable[..., bool]45 URLDefaultCallable = t.Callable[[str, dict], None]46 URLValuePreprocessorCallable = t.Callable[[t.Optional[str], t.Optional[dict]], None]47+48 # This should take Exception, but that either breaks typing the argument49 # with a specific exception, or decorating multiple times with different50 # exceptions (and using a union type on the argument).51 # https://github.com/pallets/flask/issues/409552 # https://github.com/pallets/flask/issues/429553 # https://github.com/pallets/flask/issues/429754 ErrorHandlerCallable = t.Callable[[t.Any], ResponseReturnValue]55+ErrorHandlerDecorator = t.TypeVar("ErrorHandlerDecorator", bound=ErrorHandlerCallable)56+57+ViewCallable = t.Callable[..., ResponseReturnValue]58+RouteDecorator = t.TypeVar("RouteDecorator", bound=ViewCallable)added:tests/typing/typing_error_handler.py+33 added
1+from __future__ import annotations2+3+from http import HTTPStatus4+5+from werkzeug.exceptions import BadRequest6+from werkzeug.exceptions import NotFound7+8+from flask import Flask9+10+app = Flask(__name__)11+12+13+@app.errorhandler(400)14+@app.errorhandler(HTTPStatus.BAD_REQUEST)15+@app.errorhandler(BadRequest)16+def handle_400(e: BadRequest) -> str:17+ return ""18+19+20+@app.errorhandler(ValueError)21+def handle_custom(e: ValueError) -> str:22+ return ""23+24+25+@app.errorhandler(ValueError)26+def handle_accept_base(e: Exception) -> str:27+ return ""28+29+30+@app.errorhandler(BadRequest)31+@app.errorhandler(404)32+def handle_multiple(e: BadRequest | NotFound) -> str:33+ return ""added:tests/typing/typing_route.py+62 added
1+from __future__ import annotations2+3+from http import HTTPStatus4+5+from flask import Flask6+from flask import jsonify7+from flask.templating import render_template8+from flask.views import View9+from flask.wrappers import Response10+11+app = Flask(__name__)12+13+14+@app.route("/str")15+def hello_str() -> str:16+ return "<p>Hello, World!</p>"17+18+19+@app.route("/bytes")20+def hello_bytes() -> bytes:21+ return b"<p>Hello, World!</p>"22+23+24+@app.route("/json")25+def hello_json() -> Response:26+ return jsonify({"response": "Hello, World!"})27+28+29+@app.route("/status")30+@app.route("/status/<int:code>")31+def tuple_status(code: int = 200) -> tuple[str, int]:32+ return "hello", code33+34+35+@app.route("/status-enum")36+def tuple_status_enum() -> tuple[str, int]:37+ return "hello", HTTPStatus.OK38+39+40+@app.route("/headers")41+def tuple_headers() -> tuple[str, dict[str, str]]:42+ return "Hello, World!", {"Content-Type": "text/plain"}43+44+45+@app.route("/template")46+@app.route("/template/<name>")47+def return_template(name: str | None = None) -> str:48+ return render_template("index.html", name=name)49+50+51+class RenderTemplateView(View):52+ def __init__(self: RenderTemplateView, template_name: str) -> None:53+ self.template_name = template_name54+55+ def dispatch_request(self: RenderTemplateView) -> str:56+ return render_template(self.template_name)57+58+59+app.add_url_rule(60+ "/about",61+ view_func=RenderTemplateView.as_view("about_page", template_name="about.html"),62+)modified:setup.cfg+1 added-1 removed
85 unmodified lines86 # __init__ exports names87 src/flask/__init__.py: F40188 89 [mypy]90-files = src/flask90+files = src/flask, tests/typing91 python_version = 3.792 show_error_codes = True93 allow_redefinition = True94 disallow_subclassing_any = True27 unmodified lines