From 4bf7415a9692b0c1a69cd50a17c1cbda4a75931b Mon Sep 17 00:00:00 2001 From: Matthijs van der Vleuten Date: Thu, 14 Jul 2022 11:22:22 +0200 Subject: [PATCH] allow TypedDict as a response value --- CHANGES.rst | 2 ++ src/flask/typing.py | 3 ++- tests/typing/typing_route.py | 11 +++++++++++ 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/CHANGES.rst b/CHANGES.rst index 018c680d..95a004d7 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -91,6 +91,8 @@ Unreleased - Allow returning a list from a view function, to convert it to a JSON response like a dict is. :issue:`4672` +- When type checking, allow ``TypedDict`` to be returned from view + functions. :pr:`4695` Version 2.1.3 diff --git a/src/flask/typing.py b/src/flask/typing.py index 89bdc71e..8857598e 100644 --- a/src/flask/typing.py +++ b/src/flask/typing.py @@ -11,7 +11,8 @@ ResponseValue = t.Union[ str, bytes, t.List[t.Any], - t.Dict[str, t.Any], + # Only dict is actually accepted, but Mapping allows for TypedDict. + t.Mapping[str, t.Any], t.Iterator[str], t.Iterator[bytes], ] diff --git a/tests/typing/typing_route.py b/tests/typing/typing_route.py index 5f2ddbfd..566280c0 100644 --- a/tests/typing/typing_route.py +++ b/tests/typing/typing_route.py @@ -3,6 +3,8 @@ from __future__ import annotations import typing as t from http import HTTPStatus +import typing_extensions as te + from flask import Flask from flask import jsonify from flask import stream_template @@ -38,6 +40,15 @@ def hello_json_list() -> t.List[t.Any]: return [{"message": "Hello"}, {"message": "World"}] +class StatusJSON(te.TypedDict): + status: str + + +@app.route("/typed-dict") +def typed_dict() -> StatusJSON: + return {"status": "ok"} + + @app.route("/generator") def hello_generator() -> t.Generator[str, None, None]: def show() -> t.Generator[str, None, None]: