view function is actually type checked
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 8c6f1d9 · Browse files · 5 files·+63 added−45 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+63 added−45 removed
- tests:+28 added−19 removed
- other:+35 added−26 removed
Provenance
- Commit
81be290- Tree
1af55d0- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
8c6f1d9
5 files changed+63 added−45 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+1 added-1 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 for198 unmodified linesmodified:src/flask/scaffold.py+21 added-9 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 building415 unmodified linesmodified:src/flask/typing.py+11 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+56+ViewCallable = t.Callable[..., ResponseReturnValue]57+RouteDecorator = t.TypeVar("RouteDecorator", bound=ViewCallable)modified:tests/typing/typing_route.py+28 added-19 removed
1+from __future__ import annotations2+3 from http import HTTPStatus2-from typing import Tuple3-from typing import Union4 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-11 app = Flask(__name__)12 13 15-@app.route("/")16-def hello_world() -> str: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")21-def hello_world_json() -> Response:25+def hello_json() -> Response:26 return jsonify({"response": "Hello, World!"})27 28 25-@app.route("/template")26-@app.route("/template/<name>")27-def return_template(name: Union[str, None] = None) -> str:28- return render_template("index.html", name=name)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 31-@app.errorhandler(HTTPStatus.INTERNAL_SERVER_ERROR)32-def error_500(e) -> Tuple[str, int]:33- return "<p>Sorry, we are having problems</p>", HTTPStatus.INTERNAL_SERVER_ERROR35+@app.route("/status-enum")36+def tuple_status_enum() -> tuple[str, int]:37+ return "hello", HTTPStatus.OK38 39 36-@app.before_request37-def before_request() -> None:38- app.logger.debug("Executing a sample before_request function")39- return None40+@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):43- def __init__(self: "RenderTemplateView", template_name: str) -> None:52+ def __init__(self: RenderTemplateView, template_name: str) -> None:53 self.template_name = template_name54 46- def dispatch_request(self: "RenderTemplateView") -> str:55+ def dispatch_request(self: RenderTemplateView) -> str:56 return render_template(self.template_name)57 58 59 app.add_url_rule(3 unmodified lines