Skip to content
Myr

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

5 files+63 added−45 removed

modified:src/flask/app.py+2 added-2 removed
1031 unmodified lines
1032 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 lines
1680 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 lines
modified:src/flask/blueprints.py+1 added-1 removed
382 unmodified lines
383 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 for
198 unmodified lines
modified:src/flask/scaffold.py+21 added-9 removed
361 unmodified lines
362 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.")369370 return self.route(rule, methods=[method], **options)371372 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"]``.376377 .. versionadded:: 2.0378 """379 return self._method_route("GET", rule, options)380379 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"]``.385386 .. versionadded:: 2.0387 """388 return self._method_route("POST", rule, options)389386 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"]``.394395 .. versionadded:: 2.0396 """397 return self._method_route("PUT", rule, options)398393 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"]``.403404 .. versionadded:: 2.0405 """406 return self._method_route("DELETE", rule, options)407400 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"]``.412413 .. versionadded:: 2.0414 """415 return self._method_route("PATCH", rule, options)416407 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 lines
439 :param options: Extra options passed to the440 :class:`~werkzeug.routing.Rule` object.441 """442431 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 lines
451 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 building
415 unmodified lines
modified:src/flask/typing.py+11 added-14 removed
1import typing as t233if t.TYPE_CHECKING:4 from _typeshed.wsgi import WSGIApplication # noqa: F4015 from werkzeug.datastructures import Headers # noqa: F4016 from werkzeug.wrappers import Response # noqa: F40178# The possible types that are directly convertible or are a Response object.10ResponseValue = 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]18StatusCode = int9ResponseValue = t.Union["Response", str, bytes, t.Dict[str, t.Any]]1011# the possible types for an individual HTTP header21HeaderName = str12# This should be a Union, but mypy doesn't pass unless it's a TypeVar.13HeaderValue = t.Union[str, t.List[str], t.Tuple[str, ...]]1415# the possible types for HTTP headers16HeadersValue = 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]2122# The possible types returned by a route function.23ResponseReturnValue = 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]3031# Allow any subclass of werkzeug.Response, such as the one from Flask,
11 unmodified lines
43TemplateGlobalCallable = t.Callable[..., t.Any]44TemplateTestCallable = t.Callable[..., bool]45URLDefaultCallable = t.Callable[[str, dict], None]46URLValuePreprocessorCallable = t.Callable[[t.Optional[str], t.Optional[dict]], None]4748# 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/429754ErrorHandlerCallable = t.Callable[[t.Any], ResponseReturnValue]5556ViewCallable = t.Callable[..., ResponseReturnValue]57RouteDecorator = t.TypeVar("RouteDecorator", bound=ViewCallable)
modified:tests/typing/typing_route.py+28 added-19 removed
1from __future__ import annotations23from http import HTTPStatus2from typing import Tuple3from typing import Union45from flask import Flask6from flask import jsonify7from flask.templating import render_template8from flask.views import View9from flask.wrappers import Response101111app = Flask(__name__)121315@app.route("/")16def hello_world() -> str:14@app.route("/str")15def hello_str() -> str:16 return "<p>Hello, World!</p>"171819@app.route("/bytes")20def hello_bytes() -> bytes:21 return b"<p>Hello, World!</p>"222324@app.route("/json")21def hello_world_json() -> Response:25def hello_json() -> Response:26 return jsonify({"response": "Hello, World!"})272825@app.route("/template")26@app.route("/template/<name>")27def 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>")31def tuple_status(code: int = 200) -> tuple[str, int]:32 return "hello", code333431@app.errorhandler(HTTPStatus.INTERNAL_SERVER_ERROR)32def error_500(e) -> Tuple[str, int]:33 return "<p>Sorry, we are having problems</p>", HTTPStatus.INTERNAL_SERVER_ERROR35@app.route("/status-enum")36def tuple_status_enum() -> tuple[str, int]:37 return "hello", HTTPStatus.OK383936@app.before_request37def before_request() -> None:38 app.logger.debug("Executing a sample before_request function")39 return None40@app.route("/headers")41def tuple_headers() -> tuple[str, dict[str, str]]:42 return "Hello, World!", {"Content-Type": "text/plain"}434445@app.route("/template")46@app.route("/template/<name>")47def return_template(name: str | None = None) -> str:48 return render_template("index.html", name=name)495051class 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_name5446 def dispatch_request(self: "RenderTemplateView") -> str:55 def dispatch_request(self: RenderTemplateView) -> str:56 return render_template(self.template_name)575859app.add_url_rule(
3 unmodified lines