【FastAPI】路径参数(二)

预设值¶

如果你有一个接收路径参数的路径操作,但你希望预先设定可能的有效参数值,则可以使用标准的 Python Enum 类型。

导入 Enum 并创建一个继承自 str 和 Enum 的子类。通过从 str 继承,API 文档将能够知道这些值必须为 string 类型并且能够正确地展示出来。

然后创建具有固定值的类属性,这些固定值将是可用的有效值:

声明路径参数

用你定义的枚举类(ModelName)创建一个带有类型标注的路径参数:

dart 复制代码
from enum import Enum

from fastapi import FastAPI


class ModelName(str, Enum):
    alexnet = "alexnet"
    resnet = "resnet"
    lenet = "lenet"


app = FastAPI()


@app.get("/models/{model_name}")
async def get_model(model_name: ModelName):
    if model_name is ModelName.alexnet:
        return {"model_name": model_name, "message": "Deep Learning FTW!"}

    if model_name.value == "lenet":
        return {"model_name": model_name, "message": "LeCNN all the images"}

    return {"model_name": model_name, "message": "Have some residuals"}

打开文档后出现了可选的选项,在就是枚举类型的结果

相关推荐
曲幽6 小时前
我用了FastApiAdmin后,连夜把踩过的坑都整理出来了
redis·python·postgresql·vue3·fastapi·web·sqlalchemy·admin·fastapiadmin
dinl_vin16 小时前
FastAPI 系列 ·(四):数据库集成——SQLAlchemy 2.0 异步 ORM 与 Alembic 迁移
java·数据库·fastapi
还是鼠鼠18 小时前
AI掘金头条新闻系统 (Toutiao News)-相关推荐
后端·python·mysql·fastapi·web
Just Jump19 小时前
Python 企业级主流异步 Web 框架:FastAPI vs Tornado
fastapi·tornado·异步web框架
小趴菜不能喝20 小时前
Python FastAPI
fastapi
向上的车轮21 小时前
NestJS、Spring Cloud、FastAPI、Django 深度对比分析报告
spring cloud·django·fastapi
Just Jump2 天前
2个框架(Tornado/FastAPI)、3个模块(threading/ThreadPoolExecutor/asyncio)的高并发异步实现和对比理解
fastapi·tornado·异步高并发
Li emily3 天前
解决了加密货币api多币种订阅时的数据乱序问题
人工智能·python·api·fastapi
Muyuan19984 天前
31.Cursor 初体验:用 AI Agent 给 PaperPilot 做一次最小工程重构
人工智能·python·重构·django·fastapi·faiss
csdn小瓯4 天前
FastAPI 依赖注入与状态管理实战:构建高可维护的异步后端
fastapi