首页 > 其他分享 >三周精通FastAPI:17 Path Operation Configuration路径操作配置

三周精通FastAPI:17 Path Operation Configuration路径操作配置

时间:2024-10-27 13:51:59浏览次数:3  
标签:None description 17 tags FastAPI app item import Path

路径操作配置

路径操作装饰器支持多种配置参数。

"警告"

注意:以下参数应直接传递给路径操作装饰器,不能传递给路径操作函数

status_code 状态码

status_code 用于定义路径操作响应中的 HTTP 状态码。

可以直接传递 int 代码, 比如 404。如果记不住数字码的涵义,也可以用 status 的快捷常量:

from typing import Set, Union

from fastapi import FastAPI, status
from pydantic import BaseModel

app = FastAPI()


class Item(BaseModel):
    name: str
    description: Union[str, None] = None
    price: float
    tax: Union[float, None] = None
    tags: Set[str] = set()


@app.post("/items/", response_model=Item, status_code=status.HTTP_201_CREATED)
async def create_item(item: Item):
    return item

状态码在响应中使用,并会被添加到 OpenAPI 概图。

"技术细节"

也可以使用 from starlette import status 导入状态码。

FastAPI 的fastapi.status 和 starlette.status 一样,只是快捷方式。实际上,fastapi.status 直接继承自 Starlette。

tags 参数

tags 参数的值是由 str 组成的 list (一般只有一个 str ),tags 用于为路径操作添加标签:

from typing import Set, Union

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()


class Item(BaseModel):
    name: str
    description: Union[str, None] = None
    price: float
    tax: Union[float, None] = None
    tags: Set[str] = set()


@app.post("/items/", response_model=Item, tags=["items"])
async def create_item(item: Item):
    return item


@app.get("/items/", tags=["items"])
async def read_items():
    return [{"name": "Foo", "price": 42}]


@app.get("/users/", tags=["users"])
async def read_users():
    return [{"username": "johndoe"}]

OpenAPI 概图会自动添加标签,供 API 文档接口使用:

summary 和 description 参数

路径装饰器还支持 summary 和 description 这两个参数:

from typing import Set, Union

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()


class Item(BaseModel):
    name: str
    description: Union[str, None] = None
    price: float
    tax: Union[float, None] = None
    tags: Set[str] = set()


@app.post(
    "/items/",
    response_model=Item,
    summary="Create an item",
    description="Create an item with all the information, name, description, price, tax and a set of unique tags",
)
async def create_item(item: Item):
    return item

文档字符串(docstring

描述内容比较长且占用多行时,可以在函数的 docstring 中声明路径操作的描述,FastAPI 支持从文档字符串中读取描述内容。文档字符串支持 Markdown,能正确解析和显示 Markdown 的内容,但要注意文档字符串的缩进。

from typing import Set, Union

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()


class Item(BaseModel):
    name: str
    description: Union[str, None] = None
    price: float
    tax: Union[float, None] = None
    tags: Set[str] = set()


@app.post("/items/", response_model=Item, summary="Create an item")
async def create_item(item: Item):
    """
    Create an item with all the information:

    - **name**: each item must have a name
    - **description**: a long description
    - **price**: required
    - **tax**: if the item doesn't have tax, you can omit this
    - **tags**: a set of unique tag strings for this item
    """
    return item

下图为 Markdown 文本在 API 文档中的显示效果:

响应描述

response_description 参数用于定义响应的描述说明:

from typing import Set, Union

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()


class Item(BaseModel):
    name: str
    description: Union[str, None] = None
    price: float
    tax: Union[float, None] = None
    tags: Set[str] = set()


@app.post(
    "/items/",
    response_model=Item,
    summary="Create an item",
    response_description="The created item",
)
async def create_item(item: Item):
    """
    Create an item with all the information:

    - **name**: each item must have a name
    - **description**: a long description
    - **price**: required
    - **tax**: if the item doesn't have tax, you can omit this
    - **tags**: a set of unique tag strings for this item
    """
    return item

"说明"

注意,response_description 只用于描述响应,description 一般则用于描述路径操作

"检查"

OpenAPI 规定每个路径操作都要有响应描述。

如果没有定义响应描述,FastAPI 则自动生成内容为 "Successful response" 的响应描述。

 

弃用路径操作

deprecated 参数可以把路径操作标记为弃用,无需直接删除:

from fastapi import FastAPI

app = FastAPI()


@app.get("/items/", tags=["items"])
async def read_items():
    return [{"name": "Foo", "price": 42}]


@app.get("/users/", tags=["users"])
async def read_users():
    return [{"username": "johndoe"}]


@app.get("/elements/", tags=["items"], deprecated=True)
async def read_elements():
    return [{"item_id": "Foo"}]

API 文档会把该路径操作标记为弃用:

下图显示了正常路径操作与弃用路径操作 的区别:

小结

通过传递参数给路径操作装饰器 ,即可轻松地配置路径操作、添加元数据。

实践

用一个综合代码片段进行实践

源代码

将代码写入pathop.py文件

from typing import Set, Union

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()


class Item(BaseModel):
    name: str
    description: Union[str, None] = None
    price: float
    tax: Union[float, None] = None
    tags: Set[str] = set()


@app.post(
    "/items/",
    response_model=Item,
    summary="Create an item",
    # description="Create an item with all the information, name, description, price, tax and a set of unique tags",
    response_description="The created item",
)
async def create_item(item: Item):
    """
    Create an item with all the information:

    - **name**: each item must have a name
    - **description**: a long description
    - **price**: required
    - **tax**: if the item doesn't have tax, you can omit this
    - **tags**: a set of unique tag strings for this item
    """
    return item


@app.get("/elements/", tags=["items"], deprecated=True)
async def read_elements():
    return [{"item_id": "Foo"}]

启动服务

uvicorn pathop:app --reload

测试服务

浏览器浏览docs

浏览网址:http://127.0.0.1:8000/docs

仔细观察设定的tags、summary以及文档字符串等。

 

curl命令进行测试

curl -X POST "http://127.0.0.1:8000/items/" -H "Content-Type: application/json" -d '{ "name": "Example Item", "description": "This is an example item description.", "price": 19.99, "tax": 2.5, "tags": ["example", "test"]  }'

输出:

{"name":"Example Item","description":"This is an example item description.","price":19.99,"tax":2.5,"tags":["example","test"]}

 

总结:

实践中获得:

若写了description参数,则文档字符串不显示。

弃用还是可以用curl通信的

curl -X GET "http://127.0.0.1:8000/elements/"
[{"item_id":"Foo"}]

标签:None,description,17,tags,FastAPI,app,item,import,Path
From: https://blog.csdn.net/skywalk8163/article/details/143267353

相关文章

  • 轻松构建高效 API:FastAPI 的主要特点与实战应用20241027
    轻松构建高效API:FastAPI的主要特点与实战应用引言在现代应用开发中,API的高效性和易用性至关重要。FastAPI作为一个新兴的Python框架,以其独特的设计理念和强大的功能迅速赢得了开发者的青睐。本文将从FastAPI的主要特点出发,探讨其在实际应用中的优势与最佳实践,帮助......
  • 学期 2024-2025-1 学号20241317 《计算机基础与程序设计》第五周学习总结
    学期2024-2025-1学号20241317《计算机基础与程序设计》第五周学习总结作业信息这个作业属于哪个课程<班级的链接>(如2024-2025-1-计算机基础与程序设计)这个作业要求在哪里<作业要求的链接>(如2024-2025-1计算机基础与程序设计第一周作业)这个作业的目标<写上具......
  • redis高级篇之IO多路复用select方法简介 第174节答疑
    1、bitmap最大1024位,一个进程最多只能处理1024个客户端2、&rset不可重用,每次socket有数据就相应的位会被置位3、文件描述符数组拷贝到了内核态(只不过无系统调用切换上下文的开销。(内核层可优化为异步事件通知)),仍然有开销。select调用需要传入fd数组,需要拷贝一份到内核,高......
  • redis高级篇之IO多路复用IOMultiplexing从学术到人话版 172节答疑
    ref:selectRecieve.png这图什么意思,select是阻塞的,然后呢?这张图展示了I/O复用模式下的工作流程,特别是使用`select`系统调用进行I/O复用的情况。在这种模式下,`select`用于监听多个文件描述符(如套接字),等待其中任何一个变为可读、可写或有异常发生。以下是图中各部分的详......
  • 数据结构:(OJ917)仅仅反转字母
    给你一个字符串 s ,根据下述规则反转字符串:所有非英文字母保留在原有位置。所有英文字母(小写或大写)位置反转。返回反转后的 s 。示例1:输入:s="ab-cd"输出:"dc-ba"示例2:输入:s="a-bC-dEf-ghIj"输出:"j-Ih-gfE-dCba"示例3:输入:s="Test1ng-Leet=code-Q!"输出:"......
  • ctfshow的sql注入解题思路171-211
    ctfshow-SQL注入web171:爆库名->爆表名->爆字段名->爆字段值-1'unionselect1,database(),3--+//返回数据库名-1'unionselect1,2,group_concat(table_name)frominformation_schema.tableswheretable_schema='库名'--+//获取数据库里的表名-1'unionselect......
  • 三周精通FastAPI:14 表单数据和表单模型Form Models
     官网文档:表单数据-FastAPI表单数据¶接收的不是JSON,而是表单字段时,要使用 Form表单。fromfastapiimportFastAPI,Formapp=FastAPI()@app.post("/login/")asyncdeflogin(username:str=Form(),password:str=Form()):return{"username":user......
  • 三周精通FastAPI:8 请求体 - 多个参数、字段、嵌套模型
    本节内容对应FastAPI手册的三节,分别是请求体-多个参数,请求体-字段和请求体-嵌套模型。手册: https://fastapi.tiangolo.com/zh/tutorial/body-multiple-params/源代码示例是python3.10及以上版本。请求体-多个参数¶既然我们已经知道了如何使用 Path 和 Query,下面让......
  • 三周精通FastAPI:10 Cookie 参数 和Cookie 参数模型
    官方文档:Cookie参数-FastAPICookie参数¶定义 Cookie 参数与定义 Query 和 Path 参数一样。源码:fromtypingimportAnnotatedfromfastapiimportCookie,FastAPIapp=FastAPI()@app.get("/items/")asyncdefread_items(ads_id:Annotated[str|Non......
  • 架构设计(17)大数据框架Hadoop与基础架构CDH
    HadoopHadoop是一个开源的大数据处理框架,由Apache软件基金会开发。它主要用于存储和处理大规模数据集,能够在分布式计算环境中有效工作。以下是Hadoop的详细介绍,包括其核心组件、架构、特性和应用场景。1.Hadoop的架构Hadoop的架构分为两个主要部分:Hadoop分布式文件系......