响应返回值#

响应函数可以返回多种不同类型的响应值,这些值将触发对客户端的不同响应。可能的直接返回值有:

响应值#

str#

return "Hello"
return await render_template("index.html")

单独的字符串返回值表示您打算返回字符串 mimetype text/html。该字符串将使用默认的 charset 进行编码。

dict#

return {"a": "b"}

单独的字典返回值表示您打算返回 json,application/json。将使用 jsonify 函数来对字典进行编码。

list#

return ["a", "b"]

单独的列表返回值表示您打算返回 json,application/json。将使用 jsonify 函数来对列表进行编码。

Response#

@app.route('/')
async def route_func():
    return Response("Hello")

返回 Response 实例表示您确切地知道要返回什么。

AsyncGenerator[bytes, None]#

@app.route('/')
async def route_func():

    async def agen():
        data = await something
        yield data

    return agen()

返回异步生成器允许将响应流式传输到客户端,从而降低峰值内存使用量,如果与具有值 chunkedTransfer-Encoding 标头结合使用。

Generator[bytes, None, None]#

@app.route('/')
async def route_func():

    def gen():
        yield data

    return gen()

返回生成器允许将响应流式传输到客户端,从而降低峰值内存使用量,如果与具有值 chunkedTransfer-Encoding 标头结合使用。

组合#

上述任何响应值都可以组合,如下所述:

Tuple[ResponseValue, int]#

@app.route('/')
async def route_func():
    return "Hello", 200

包含响应值和整数的元组表示您打算指定状态代码。

Tuple[str, int, Dict[str, str]]#

@app.route('/')
async def route_func():
    return "Hello", 200, {'X-Header': 'Value'}

包含响应值、整数和字典的元组表示您打算指定其他标头。