Skip to content
Myr

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

7 files+138 added−31 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+5 added-3 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
168 unmodified lines
560 lambda s: s.app.template_context_processors.setdefault(None, []).append(f)561 )562 return f563564 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 """570569 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 f574575 return decorator
16 unmodified lines
modified:src/flask/scaffold.py+23 added-11 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
193 unmodified lines
653654 @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.659660 A decorator that is used to register a function given an661 error code. Example::
21 unmodified lines
683 :param code_or_exception: the code as integer for the handler, or684 an arbitrary exception685 """686675 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 f690691 return decorator
183 unmodified lines
modified:src/flask/typing.py+12 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]55ErrorHandlerDecorator = t.TypeVar("ErrorHandlerDecorator", bound=ErrorHandlerCallable)5657ViewCallable = t.Callable[..., ResponseReturnValue]58RouteDecorator = t.TypeVar("RouteDecorator", bound=ViewCallable)
added:tests/typing/typing_error_handler.py+33 added
1from __future__ import annotations23from http import HTTPStatus45from werkzeug.exceptions import BadRequest6from werkzeug.exceptions import NotFound78from flask import Flask910app = Flask(__name__)111213@app.errorhandler(400)14@app.errorhandler(HTTPStatus.BAD_REQUEST)15@app.errorhandler(BadRequest)16def handle_400(e: BadRequest) -> str:17 return ""181920@app.errorhandler(ValueError)21def handle_custom(e: ValueError) -> str:22 return ""232425@app.errorhandler(ValueError)26def handle_accept_base(e: Exception) -> str:27 return ""282930@app.errorhandler(BadRequest)31@app.errorhandler(404)32def handle_multiple(e: BadRequest | NotFound) -> str:33 return ""
added:tests/typing/typing_route.py+62 added
1from __future__ import annotations23from http import HTTPStatus45from flask import Flask6from flask import jsonify7from flask.templating import render_template8from flask.views import View9from flask.wrappers import Response1011app = Flask(__name__)121314@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")25def hello_json() -> Response:26 return jsonify({"response": "Hello, World!"})272829@app.route("/status")30@app.route("/status/<int:code>")31def tuple_status(code: int = 200) -> tuple[str, int]:32 return "hello", code333435@app.route("/status-enum")36def tuple_status_enum() -> tuple[str, int]:37 return "hello", HTTPStatus.OK383940@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):52 def __init__(self: RenderTemplateView, template_name: str) -> None:53 self.template_name = template_name5455 def dispatch_request(self: RenderTemplateView) -> str:56 return render_template(self.template_name)575859app.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 lines
86 # __init__ exports names87 src/flask/__init__.py: F4018889[mypy]90files = src/flask90files = src/flask, tests/typing91python_version = 3.792show_error_codes = True93allow_redefinition = True94disallow_subclassing_any = True
27 unmodified lines