FastAPI 基础学习(十四) Response自定义状态码

作者:麦克煎蛋   出处:https://www.cnblogs.com/mazhiyong/ 转载请保留这段声明,谢谢!

一、通过参数status_code自定义状态码

我们可以用参数status_code来声明Response状态码。

支持任意路径操作:

@app.get()
@app.post()
@app.put()
@app.delete()
from fastapi import FastAPI

app = FastAPI()


@app.post("/items/", status_code=201)
async def create_item(name: str):
    return {"name": name}

参数status_code接收一个数字内容,作为HTTP状态码。并且会在response中返回这个状态码,同时会在文档中记录。

注意status_code是装饰器方法(get,post等)的参数。

我们可以从 fastapi.status 导入状态码常量,便于使用和记忆。

from fastapi import FastAPI, status

app = FastAPI()


@app.post("/items/", status_code=status.HTTP_201_CREATED)
async def create_item(name: str):
    return {"name": name}

二、通过Response参数自定义状态码

我们可以在路径操作函数中声明Response参数,然后给这个临时的Response对象设置status_code信息。

FastAPI通过这个临时的Response对象解析出status_code信息(以及header、cookie信息等),然后放入到最终返回的Response对象中。

我们也可以在依赖项中使用Response参数,然后设置status_code信息(以及其他信息)。

from fastapi import FastAPI, Response, status

app = FastAPI()

tasks = {"foo": "Listen to the Bar Fighters"}


@app.put("/get-or-create-task/{task_id}", status_code=200)
def get_or_create_task(task_id: str, response: Response):
if task_id not in tasks:
        tasks[task_id] = "This didn't exist before" response.status_code = status.HTTP_201_CREATED
return tasks[task_id]

三、通过直接返回Response自定义状态码

FastAPI默认情况下会通过JSONResponse返回请求结果,返回的状态码是默认状态码或者是路径操作中设置的状态码。

如果我们想自定义状态码,可以通过直接返回Response对象来设置状态码,比如直接返回JSONResponse对象。

如下示例,我们需要先导入JSONResponse,然后自定义状态码,直接返回数据对象。

from typing import Optional

from fastapi import Body, FastAPI, status
from fastapi.responses import JSONResponse

app = FastAPI()

items = {"foo": {"name": "Fighters", "size": 6}, "bar": {"name": "Tenders", "size": 3}}


@app.put("/items/{item_id}")
async def upsert_item(item_id: str, name: Optional[str] = Body(None), size: Optional[int] = Body(None)):
    if item_id in items:
        item = items[item_id]
        item["name"] = name
        item["size"] = size
        return item
    else:
        item = {"name": name, "size": size}
        items[item_id] = item
        return JSONResponse(status_code=status.HTTP_201_CREATED, content=item)
原文地址:https://www.cnblogs.com/mazhiyong/p/12957121.html