FastApi学习-05

异常控制(http status code)

@app.get("/request01")
def request01():
    raise HTTPException(status_code=401, detail={"custom": "自定义数据类型"}, headers={"Err-Msg": "123"})
    return "hello world"

class MyException(Exception):
    def __init__(self, msg):
        self.msg = msg

@app.exception_handler(MyException)
async def my_exception_handler(request: Request, e: MyException):
    return JSONResponse(
        status_code=418,
        content={"message": f"{e.msg}", "data": 123},
    )

@app.get("/request02")
def request02():
    raise MyException(msg="123")
    return "hello world"

@app.exception_handler(RequestValidationError)
async def my_request_validation_exception(request: Request, e: RequestValidationError):
    # 解析RequestValidationError的数据,重新拼接返回
    rtype = e.raw_errors[0].loc_tuple()[0]
    rkey = e.raw_errors[0].loc_tuple()[1]
    msg = e.raw_errors[0].exc.msg_template
    return JSONResponse(
        status_code=418,
        content=[rtype, rkey, msg]
    )

@app.exception_handler(SelfException)
async def my_exception_handler1(request: Request, e: HTTPException):
    print("hello exception")
    return await http_exception_handler(request, e)

@app.get("/request03")
def request03(num: int = Query(...)):
    return "hello world"

request01:使用raise抛出自定义的HTTPException,可以自定义status_code(这个status_code是在标准内的),可以定义返回的内容detail,也可以增加自定义的headers.

request02:自定义Exception,返回标准的status_code和自定义的content

my_request_validation_exception方法:覆盖其他的Exception,实现自定义功能

my_request_handler1方法:复用其他的Exception Handler,实现自定义功能

API文档配置

在@app.get()装饰器中加入响应的配置参数,优化API文档的显示。

@app.get("/request04", status_code=status.HTTP_401_UNAUTHORIZED, tags=["request"], summary="1", description="1",
         response_description="1", deprecated=True)
def request04():
    return "hello world"

status_code: 如果没有异常或者手动的抛出异常,都会返回指定的status_code

tags: 为该接口分组标示

summary, description, response_description:都是一些描述性文字,便于接口功能的理解

deprecated: 申明是否废弃,但是不影响接口的调用,只是在文档中标注废弃。

jsonable_encoder BaseModel转dict或者list

class Item(BaseModel):
    a: datetime
    b: date
    c: int
    d: str
    e: bool

@app.post("/request05")
def request05(item: Item):
    item1 = jsonable_encoder(item)
    print(type(item1))
    return item

@app.post("/request06")
def request06(item: List[Item]):
    item1 = jsonable_encoder(item)
    print(type(item1))
    return item

通过jsonable_encoder转成对应的dict或者list,但是datetime,date,time会转化成标准化的时间字符串

BaseModel的数据变换

在实际的业务中,会遇到各种情况对数据进行变换。

@app.post("/request07")
def request07(item: Item):
    print(item.dict(by_alias=True))
    print(item.dict(exclude_unset=True))
    print(item.dict(exclude_none=True))
    print(item.dict(exclude_defaults=True))
    print(item.dict(exclude={"c", "d"}))
    # copy方法
    item1 = {"d": 1993}
    print(item1)
    item2 = item.copy(update=item1, deep=True)
    return item2

BaseModel的dict()方法

by_alias: 转化成dict的时候,key使用BaseModel中设置的alias_name

exclude_unset: 转化成dict的时候,对于request-body中未设置的数据忽略,exclude_defaults和exclude_unset差不多。

exclude_none: 转化成dict的时候,忽略值是None的key

exclude: 传入转化成dict的时候,不需要的field

BaseModel的copy()方法

deep: 是否是深拷贝。

update:以dict数据更新item。然后复制给item2

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
fastapi-mysql-generator 是一个用于快速生成FastAPI和MySQL的框架的工具。FastAPI是一个现代、快速(高性能)的web框架,而MySQL是一个流行的关系型数据库。 使用 fastapi-mysql-generator,可以从一个简单的命令行界面中生成 FastAPI 应用程序,并与 MySQL 数据库集成。这个工具可以自动创建数据库表和模型(Model),并提供一组 API 端点,用于执行常见的 CRUD(创建、读取、更新和删除)操作。 fastapi-mysql-generator 的主要优势之一是它的简单易用性。无论是初学者还是有经验的开发人员,都可以快速上手并生成一个完整的基于FastAPI和MySQL的应用程序。只需要几个简单的步骤,就可以生成项目的基本结构和代码。同时,fastapi-mysql-generator 还提供了一些配置选项,可以根据需求进行自定义设置,以满足特定的应用程序需求。 这个工具还提供了一些有用的特性,以增强开发的效率和便利性。例如,它可以自动生成 API 文档,包括请求和响应模型的文档说明。此外,fastapi-mysql-generator 还支持身份验证和授权功能,以确保 API 路由的安全性。 总而言之,fastapi-mysql-generator 是一个快速生成 FastAPI 和 MySQL 应用程序的方便工具。它简化了应用程序的开发过程,并提供了一些有用的特性,以提高开发效率和便利性。无论是初学者还是有经验的开发人员,都可以受益于这个工具的使用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值