跳转至

响应头

🌐 Translation by AI and humans

This translation was made by AI guided by humans. 🤝

It could have mistakes of misunderstanding the original meaning, or looking unnatural, etc. 🤖

You can improve this translation by helping us guide the AI LLM better.

English version

使用 Response 参数

你可以在你的路径操作函数中声明一个 Response 类型的参数(就像你可以为 cookies 做的那样)。

然后你可以在这个临时响应对象中设置头部。

from fastapi import FastAPI, Response

app = FastAPI()


@app.get("/headers-and-object/")
def get_headers(response: Response):
    response.headers["X-Cat-Dog"] = "alone in the world"
    return {"message": "Hello World"}
🤓 Other versions and variants
from fastapi import FastAPI, Response

app = FastAPI()


@app.get("/headers-and-object/")
def get_headers(response: Response):
    response.headers["X-Cat-Dog"] = "alone in the world"
    return {"message": "Hello World"}

然后你可以像平常一样返回任何你需要的对象(例如一个 dict 或者一个数据库模型)。

如果你声明了一个 response_model,它仍然会被用来过滤和转换你返回的对象。

FastAPI 将使用这个临时响应来提取头部(也包括 cookies 和状态码),并将它们放入包含你返回的值的最终响应中,该响应由任何 response_model 过滤。

你也可以在依赖项中声明 Response 参数,并在其中设置头部(和 cookies)。

直接返回 Response

你也可以在直接返回 Response 时添加头部。

按照直接返回响应中所述创建响应,并将头部作为附加参数传递:

from fastapi import FastAPI
from fastapi.responses import JSONResponse

app = FastAPI()


@app.get("/headers/")
def get_headers():
    content = {"message": "Hello World"}
    headers = {"X-Cat-Dog": "alone in the world", "Content-Language": "en-US"}
    return JSONResponse(content=content, headers=headers)
🤓 Other versions and variants
from fastapi import FastAPI
from fastapi.responses import JSONResponse

app = FastAPI()


@app.get("/headers/")
def get_headers():
    content = {"message": "Hello World"}
    headers = {"X-Cat-Dog": "alone in the world", "Content-Language": "en-US"}
    return JSONResponse(content=content, headers=headers)

技术细节

你也可以使用 from starlette.responses import Responsefrom starlette.responses import JSONResponse

FastAPI 提供了与 fastapi.responses 相同的 starlette.responses,只是为了方便你(开发者)。但是,大多数可用的响应都直接来自 Starlette。

由于 Response 经常用于设置头部和 cookies,FastAPI 还在 fastapi.Response 中提供了它。

自定义头部

请注意,可以通过使用 X- 前缀添加自定义专有头部。

但是,如果你有自定义头部,并希望浏览器中的客户端能够看到它们,你需要将它们添加到你的 CORS 配置中(在 CORS(跨源资源共享) 中阅读更多),使用在 Starlette 的 CORS 文档中记录的 expose_headers 参数。