python - Flask View 的类型注释是什么?

标签 python flask python-typing

我想向返回对redirect的调用的 View 函数添加类型注释。 redirect 返回什么,以及如何将其注释添加到我的 View 函数中?

我认为这可能是 strredirect 函数,但我不确定。

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

最佳答案

最简单的答案是用您要返回的内容来注释您的 View 。在您的具体示例中,redirect 返回 werkzeug.wrappers.Response 的实例。

from werkzeug.wrappers import Response

def set_alarm() -> Response:
    return redirect()
<小时/>

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

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

  • strbytes
  • werkzeug.wrappers.BaseResponse 的子类。
  • 采用以下形式之一的元组,其中 data 是 Fl​​ask View 可以返回的任何其他类型:
    • (数据,)
    • (data, status),其中 status 可以是 intstr字节
    • (data, headers),其中 headers 是一个字典、可迭代的 (key, value) 元组,或者一个 werkzeug.datastructs.Headers 对象。
    • (数据、状态、 header )
  • 要转换为 JSON 的 dict。这些值应该是 app.json_encoder 支持的类型。
  • 可调用的 WSGI。

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

这里有一个view_return_type,它表示 Flask View 中可能的返回类型,ignoring JSON typing 。一旦定义了类型,您就可以用它来注释任何 View 。

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],
]
@app.route("/users/<int:id>/")
def user_detail(id: int) -> view_return_type:
    ...

关于python - Flask View 的类型注释是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58864281/

相关文章:

python - 如何注释可以转换为 bool 值的参数?

Python:将0到1之间的值转换为红色到蓝色的颜色范围

python - 如何为Python虚拟环境配置Ansible?

session - 关闭浏览器后 Flask.session 仍然存在

python - 使用来自 render_template() 的 'for' 循环在 html 中显示表格

python - Text vs str,当使用 python 类型提示时

javascript - 从脚本中的 var 中提取数据并使用 python 将 pdf 下载到文件夹

python - 优化 Pandas 多索引查找

python - 显示我的多线程进程的进度条

python - 如何向 UserDict 提供类型提示?