Flask 视图的类型注释是什么?

jh6*_*jh6 5 python flask python-typing

我想向返回调用的视图函数添加类型注释redirectredirect返回什么,我如何为我的视图函数添加注释?

我认为它可能是str,或redirect功能,但我不确定。

def setalarm() -> redirect:
    # Retrieves the information to create new alarms.
    return redirect("/")
Run Code Online (Sandbox Code Playgroud)

Pan*_*nic 10

在 Flask 2 中你可以使用flask.typing.ResponseReturnValue.

from flask.typing import ResponseReturnValue


@app.get("/")
def index() -> ResponseReturnValue:
    return "OK"
Run Code Online (Sandbox Code Playgroud)


dav*_*ism 8

直接的答案是用您正在编写的任何内容来注释您的视图以返回。在您的特定示例中,redirect返回werkzeug.wrappers.Response.

from werkzeug.wrappers import Response

def set_alarm() -> Response:
    return redirect()
Run Code Online (Sandbox Code Playgroud)

与其弄清楚任何给定的函数返回什么来注释您的视图,不如想出一个Union表示 Flask 视图允许返回的任何内容的注释似乎更容易。然而,Flask 不提供类型信息,其动态特性使得表示可能性变得困难。

默认情况下,Flask 视图可以返回:

  • Astrbytes
  • 的一个子类werkzeug.wrappers.BaseResponse
  • 这些形式之一的元组,其中dataFlask 视图可以返回的任何其他类型:
    • (data,)
    • (data, status), 其中status可以是 anint或 astrbytes
    • (data, headers), 其中headers是字典、可迭代的(key, value)元组或werkzeug.datastructures.Headers对象。
    • (data, status, headers)
  • dict要转换为 JSON 的A。值应该是app.json_encoder支持的类型。
  • 可调用的 WSGI。

Flask 可以通过覆盖该Flask.make_response方法来支持更多或不同的返回类型。它可以序列化为 JSON 的数据可以通过覆盖Flask.json_encoder. 如果您自定义了 Flask 的行为,您还需要自定义类型信息。

这是一个view_return_type代表 Flask 视图中可能的返回类型,忽略 JSON 类型。一旦你定义了类型,你就可以用它来注释任何视图。

import typing as t
from werkzeug.datastructures import Headers
from werkzeug.wrappers import BaseResponse

_str_bytes = t.Union[str, bytes]
_data_type = t.Union[
    _str_bytes,
    BaseResponse,
    t.Dict[str, t.Any],
    t.Callable[
        [t.Dict[str, t.Any], t.Callable[[str, t.List[t.Tuple[str, str]]], None]], t.Iterable[bytes]
    ],
]
_status_type = t.Union[int, _str_bytes]
_headers_type = t.Union[
    Headers, t.Dict[_str_bytes, _str_bytes], t.Iterable[t.Tuple[_str_bytes, _str_bytes]],
]

view_return_type = t.Union[
    _data_type,
    t.Tuple[_data_type],
    t.Tuple[_data_type, _status_type],
    t.Tuple[_data_type, _headers_type],
    t.Tuple[_data_type, _status_type, _headers_type],
]
Run Code Online (Sandbox Code Playgroud)
@app.route("/users/<int:id>/")
def user_detail(id: int) -> view_return_type:
    ...
Run Code Online (Sandbox Code Playgroud)