当前位置: 代码网 > it编程>前端脚本>Python > Python中FastAPI项目使用 Annotated的参数设计的处理方案

Python中FastAPI项目使用 Annotated的参数设计的处理方案

2024年08月02日 Python 我要评论
在fastapi中,你可以使用pep 593中的annotated类型来添加元数据到类型提示中。这个功能非常有用,因为它允许你在类型提示中添加更多的上下文信息,例如描述、默认值或其他自定义元数据。fa

在fastapi中,你可以使用pep 593中的annotated类型来添加元数据到类型提示中。这个功能非常有用,因为它允许你在类型提示中添加更多的上下文信息,例如描述、默认值或其他自定义元数据。

fastapi支持annotated类型,这使得你可以为路径操作函数的参数提供额外的元数据,例如依赖项、查询参数的描述、别名等。

fastapi介绍

fastapi 是一个用于构建 api 的现代、快速(高性能)web 框架,基于 python 类型提示。它的主要特点包括自动生成 openapi 和 json schema 文档、快速代码编写、简洁的代码结构、高效的性能等。fastapi 使用 starlette 作为 web 框架的核心,并使用 pydantic 进行数据验证。

fastapi 的主要特点

  • 快速

    • fastapi 的性能非常接近于 nodejs 和 go 等速度较快的语言,并且比其他基于 python 的框架如 flask 和 django 快得多。
  • 简洁

    • 通过类型提示和依赖注入,代码简洁易读。
    • 开发者可以更少的代码实现更多的功能。
  • 自动文档生成

    • fastapi 自动生成符合 openapi 规范的文档,这些文档可以通过内置的 swagger ui 和 redoc ui 查看。
    • 自动生成 json schema。
  • 数据验证

    • 基于 pydantic,fastapi 提供了强大的数据验证功能。
    • 支持复杂的数据验证和数据解析。
  • 类型提示

    • 充分利用 python 的类型提示,帮助开发者编写和维护代码。
  • 依赖注入

    • fastapi 提供了一个简单但功能强大的依赖注入系统,可以方便地管理依赖项。

fastapi 还支持以下功能:

  • 文件上传
  • 安全性(oauth2、jwt 等)
  • 后台任务
  • 流媒体响应
  • graphql
  • sql(通过 sqlalchemy 等)
  • 数据库事务
  • 后台任务

安装 fastapi 和 uvicorn

pip install fastapi
pip install "uvicorn[standard]"

fastapi 是一个非常现代化和高效的框架,非常适合用于构建高性能的 api。其自动文档生成、数据验证和依赖注入等特性,使得开发者能够更快、更安全地编写代码,并提供出色的用户体验。

fastapi项目的参数设计,这些您可以在路径操作函数参数或使用annotated的依赖函数中使用的特殊函数,用于从请求中获取数据。

它包括

  • query()
  • path()
  • body()
  • cookie()
  • header()
  • form()
  • file()

您可以直接从fastapi导入它们

from fastapi import body, cookie, file, form, header, path, query

1、query参数-查询参数

query参数是指我们在url中带有的查询参数如url/items?q=123&b=234 的类型格式。

假设我们要创建一个api,其中的查询参数需要带有描述和默认值:

from fastapi import fastapi, query
from typing import annotated
app = fastapi()
@app.get("/items/")
async def read_items(
    q: annotated[str, query(description="query string", min_length=3, max_length=50)] = "default"
):
    return {"q": q}

在这个例子中:

  • 我们导入了fastapi和query类,以及annotated类型。
  • 我们创建了一个fastapi应用实例。
  • 我们定义了一个路径操作函数read_items,它有一个查询参数q
  • 我们使用annotated类型为查询参数q添加了元数据,这些元数据包括描述、最小长度和最大长度等。
  • annotated的第一个参数是类型提示,第二个参数是与此类型相关的元数据。

annotated类型允许你将额外的元数据与类型提示关联,这在创建api时特别有用,因为它可以帮助生成更丰富的api文档并确保参数验证。

下面是一个更复杂的例子,展示了如何使用annotated类型与依赖项结合:

from fastapi import depends
def common_parameters(
    q: annotated[str, query(description="query string", min_length=3, max_length=50)] = "default"
):
    return {"q": q}
@app.get("/items/")
async def read_items(params: annotated[dict, depends(common_parameters)]):
    return params

在这个例子中:

  • 我们定义了一个依赖函数common_parameters,它返回一个包含查询参数q的字典。
  • 我们使用annotated类型和depends将这个依赖项注入到路径操作函数read_items中。
  • read_items函数返回了从依赖函数中获取的参数字典。

这种方法不仅简化了路径操作函数的参数定义,还使得代码更具可读性和可维护性。

2、path参数-路径参数

路径参数通常用于从 url 路径中提取信息。例如,如果你有一个获取用户信息的路径 /users/{user_id},你可以这样定义路径参数:

from fastapi import fastapi
from fastapi.params import path
from typing import annotated
app = fastapi()
@app.get("/users/{user_id}")
async def read_user(user_id: annotated[int, path(..., title="the id of the user to get")]):
    return {"user_id": user_id}

在这个示例中,annotated[int, path(..., title="the id of the user to get")] 表示 user_id 是一个整数,并且它是从路径中提取的参数。此外,我们还为这个参数添加了一个标题,用于生成 api 文档。

3、body参数-请求体参数

求体参数用于处理复杂的数据结构,例如 json 请求体。你可以使用 pydantic 模型来定义请求体的结构,并使用 annotated 来进一步注解这些参数。例如:

from fastapi import fastapi
from pydantic import basemodel
from typing import annotated
app = fastapi()
class user(basemodel):
    name: str
    age: int
@app.post("/users/")
async def create_user(user: annotated[user, body(..., title="the user to create")]):
    return {"user": user}

在这个示例中,annotated[user, body(..., title="the user to create")] 表示 user 参数是一个 user 模型实例,并且它来自请求体。我们同样为这个参数添加了一个标题。

有时候我们可以结合路径参数和请求体参数进行使用,如下例子:

from fastapi import fastapi, path, body
from pydantic import basemodel
from typing import annotated
app = fastapi()
class user(basemodel):
    name: str
    age: int
@app.put("/users/{user_id}")
async def update_user(
    user_id: annotated[int, path(..., title="the id of the user to update")],
    user: annotated[user, body(..., title="the new user data")]
):
    return {"user_id": user_id, "user": user}

在这个综合示例中,路径参数 user_id 和请求体参数 user 都使用了 annotated 进行注解,以明确它们的来源和意图,同时为生成的 api 文档提供了更多的上下文信息。

复杂的请求体通常包括嵌套的结构,可以使用 pydantic 模型来定义。例如:

from fastapi import fastapi
from pydantic import basemodel
from typing import list, annotated
app = fastapi()
class address(basemodel):
    street: str
    city: str
    state: str
    zip: str
class user(basemodel):
    name: str
    age: int
    addresses: list[address]
@app.post("/users/")
async def create_user(user: annotated[user, body(..., title="the user to create")]):
    return {"user": user}

在这个例子中,user 模型包含一个嵌套的 address 列表,这样你就可以在请求体中处理复杂的嵌套数据结构。

一个结合路径参数、查询参数和请求体参数的复杂示例:

from fastapi import fastapi, path, query, body
from pydantic import basemodel
from typing import annotated
app = fastapi()
class item(basemodel):
    name: str
    description: str | none = none
    price: float
    tax: float | none = none
@app.put("/items/{item_id}")
async def update_item(
    item_id: annotated[int, path(..., title="the id of the item to update")],
    q: annotated[str | none, query(none, max_length=50, title="query string")],
    item: annotated[item, body(..., title="the item to update")]
):
    result = {"item_id": item_id, "item": item}
    if q:
        result.update({"q": q})
    return result

在这个综合示例中,我们使用了路径参数 item_id、查询参数 q 和请求体参数 item,并通过 annotated 对这些参数进行注解,明确它们的来源和约束。

应用上面的处理方案,我们在项目中应用fastapi构建文档如下所示。

到此这篇关于python中fastapi项目使用 annotated的参数设计的文章就介绍到这了,更多相关python fastapi使用 annotated内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com