python-web开发

4、fastApi-响应

2023-07-29  本文已影响0人  许忠慧

一、基础语法

from fastapi import FastAPI

app = FastAPI()


# 传递 header 参数
@app.get("/", response_model=int)
def root():
    return 123

效果预览:

符合定义的返回值类型.png 不符合定义的返回值类型.png

二、自定义返回模型

基础语法:

from fastapi import FastAPI
from pydantic import BaseModel, EmailStr

app = FastAPI()


# 自定义的返回模型
class ReturnClass(BaseModel):
    name: str
    email: EmailStr


@app.get("/", response_model=ReturnClass)
def root():
    return ReturnClass

三、自定义响应状态码

在以下任意的路径操作中使用 status_code 参数来声明用于响应的 HTTP 状态码:

from fastapi import FastAPI

app = FastAPI()


@app.get("/", status_code=203)
def root():
    return "code"

效果:

不指定则使用 http默认响应码
http所有响应码查询:点击前往

可以使用fastApi提供的方法来便捷得记住响应码,这样可以通过自动补全来快速知道哪个状态码对应哪个状态

四、抛出异常

通过异常抛出, 可以自定义抛出异常

语法:

from fastapi import FastAPI, HTTPException

app = FastAPI()

items = {"foo": "The Foo Wrestlers"}


@app.get("/{item_id}")
async def read_item(item_id: str):
    if item_id not in items:
        raise HTTPException(status_code=404, detail="Item not found")
    return {"item": items[item_id]}

效果:

五、自定义异常处理

使用 @app.exception_handler修饰符可以自定义异常处理方法

语法:

from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse


class UnicornException(Exception):
    def __init__(self, name: str):
        self.name = name


app = FastAPI()


@app.exception_handler(UnicornException)
async def unicorn_exception_handler(request: Request, exc: UnicornException):
    return JSONResponse(
        status_code=418,
        content={"message": f"Oops! {exc.name} did something. There goes a rainbow..."},
    )


@app.get("/unicorns/{name}")
async def read_unicorn(name: str):
    if name == "yolo":
        raise UnicornException(name=name)
    return {"unicorn_name": name}

上一篇下一篇

猜你喜欢

热点阅读