api - 如果 URL 中有斜杠,FastAPI 不会在标头中包含 JSON 内容类型
问题描述
根据我的 URL 中是否有斜杠,FastAPI(使用 uvicorn 服务器)将省略content type: application/json
标题。我担心客户可能会无意中在其 URL 中添加斜杠,然后无法返回 JSON 响应,所以我想知道
a)这是正确的行为吗?
b)我如何在服务器端处理它?
这是一个非常简单的 FastAPI 应用程序:
from fastapi import FastAPI
app = FastAPI()
app.get("/alist")
async def alist():
somelist = [1, 2, 3, 4, 5]
return somelist
现在这里是“正确”请求的标头的样子,即没有尾部斜杠的标头:
因为带有斜杠,所以缺少 content-type: application/json,这可能会使客户端感到困惑。
所以根据我上面的问题,这正常吗?我该怎么做才能防止客户期望 JSON 响应但无意中添加了尾部斜杠的错误?
解决方案
a) 这是正确的行为吗?
- 由于重定向(HTTP 状态代码 307)而出现此行为。
- 我认为这应该自动处理。
- 所以我认为我们应该在FastAPI repo 中打开一个新问题。
b)我如何在服务器端处理它?
有许多不同的解决方案:
1 - 通过使用一个关键技巧(简单解决方案)将列表转换为字典:
from fastapi import FastAPI
app = FastAPI()
app.get("/alist")
async def alist():
somelist = [1, 2, 3, 4, 5]
return {"numbers": somelist}
2 - 通过手动添加“内容类型”标题:
使用响应:
from fastapi import FastAPI, Response
app = FastAPI()
app.get("/alist")
async def alist(response: Response):
# set content-type header to application/json
response.headers["content-type"] = "application/json"
somelist = [1, 2, 3, 4, 5]
return somelist
使用 JSONResponse :
from fastapi import FastAPI
from fastapi.responses import JSONResponse
app = FastAPI()
app.get("/alist")
async def alist():
somelist = [1, 2, 3, 4, 5]
# you can add additional headers
headers = {"X-Cat-Dog": "alone in the world", "Content-Language": "en-US"}
# json response will enforce "content-type" header to be "application/json"
return JSONResponse(content=somelist, headers=headers)
您可以在以下位置阅读有关 FastAPI 响应和标头的更多信息https://fastapi.tiangolo.com/advanced/response-headers/
推荐阅读
- browser - 当浏览器重新加载资源时,如果用户不强制清除缓存(例如 Ctrl + F5)
- powerbi - 创建的列未按预期计算
- java - while循环有问题并且没有得到预期的输出?
- google-chrome - 如何在 Chrome 中编辑 HSTS“max-age”指令?
- angular - npm 错误!awesome-typescript-loader@4.0.0-0 安装后
- docker - 在容器之间共享 Docker 容器存储卷
- mysql - 根据子模型/关系对父模型进行排序
- amazon-cognito - 通过 SPA 使用 aws amplify 的安全方式
- java - 如何在 UI 中搜索带有 '\t \n \r' 字符的文本
- laravel - 如何使用 docker-compose 运行 laravel 应用程序?