Fastapi 学习笔记之请求多个参数

文章详细介绍了如何在FastAPI应用中处理不同类型的参数,包括Path、Query和请求体参数,以及如何使用Pydantic模型进行数据验证。内容涵盖了多个请求体参数、单一值的请求体、查询参数、嵌入模型、字段验证、特殊类型校验和任意字典结构的请求体等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 混合使用 Path、Query 和请求体参数

from fastapi import FastAPI, Path
from typing import Optional
from pydantic import BaseModel
app = FastAPI()


class Item1(BaseModel):
    name: str
    price: float
    description: Optional[str] = None
    tax: Optional[float]


@app.put("/items/{item_id}")
async def update_item(
    *,
    item_id: int = Path(..., title="id of item to get", ge=0, le=1000),
    q: Optional[str] = None,
    item: Optional[Item1] = None,
):
    res = {"item_id": item_id}
    if q:
        res.update({"q": q})
    if item:
        res.update({"item": item})
    return res

2. 多个请求体参数

from pydantic import BaseModel

class Item(BaseModel):
    name: str
    price: float
    description: Optional[str] = None
    tax: Optional[float]
class User(BaseModel):
    username: str
    full_name: Optional[str] = None

@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item, user: User):
    res = {"item_id" : item_id, "item" : item, "user": user}
    return res

3. 请求体中的单一值

  • 传参时,varname : type = Body(...),如果不这么写,会被作为查询参数 ?varname=xxx

from fastapi import Body

class Item(BaseModel):
    name: str
    price: float
    description: Optional[str] = None
    tax: Optional[float]
class User(BaseModel):
    username: str
    full_name: Optional[str] = None

@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item, user: User, importance : int = Body(...)):
    res = {"item_id" : item_id, "item" : item, "user": user}
    return res

4. 多个请求体参数和查询参数

由于默认情况下单一值被解释为查询参数,因此你不必显式地添加 Query,你可以仅执行操作:q: str = None

5. 嵌入单个请求体参数

如果你只有一个请求体参数

@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item):
    res = {"item_id" : item_id, "item" : item}
    return res

如果你想写成 带 key 的 json 形式,添加一个传入参数 embed,item: Item = Body(..., embed=True)

6. 字段

可以使用 Pydantic 的 Field 在 Pydantic 模型内部声明校验和元数据

from fastapi import FastAPI, Path, Body
from typing import Optional
from pydantic import BaseModel, Field
app = FastAPI()


class Item(BaseModel):
    name: str
    price: float = Field(..., gt=0, description="price must be greater than 0")
    description: Optional[str] = Field(None, title="description of item", max_length=30)
    tax: Optional[float] = None

@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item = Body(..., embed=True)):
    res = {"item_id" : item_id, "item" : item}
    return res

Field 的工作方式和 Query、Path 和 Body 相同,包括它们的参数等等也完全相同

  • 注意,from pydantic import Field

7. 嵌套模型

7.1 List 字段

将一个属性定义为拥有子元素的类型,如 list

class Item(BaseModel):
    name: str
    price: float = Field(..., gt=0, description="price must be greater than 0")
    description: Optional[str] = Field(None, title="description of item", max_length=30)
    tax: Optional[float] = None
    tags: list = [] # 没有声明元素类型
  • 具有子类型的 List,from typing import List

tags: List[str] = []

7.2 子模型作为类型

from fastapi import FastAPI, Path, Body
from typing import Optional, List, Set
from pydantic import BaseModel, Field
app = FastAPI()

class Image(BaseModel):
    url:str
    name: str

class Item(BaseModel):
    name: str
    price: float = Field(..., gt=0, description="price must be greater than 0")
    description: Optional[str] = Field(None, title="description of item", max_length=30)
    tax: Optional[float] = None
    tags: Set[str] = []
    image: Optional[Image] = None
    

@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item = Body(..., embed=True)):
    res = {"item_id" : item_id, "item" : item}
    return res

8. 特殊类型校验

  • HttpUrl,检查是不是有效的 URL

from pydantic import BaseModel, Field, HttpUrl
app = FastAPI()

class Image(BaseModel):
    url: HttpUrl
    name: str

则上面的输入应改的地方 "url":"http://www.michael.com",否则不是有效的 URL

9. 带有一组子模型的属性

  • 更改为 image: Optional[List[Image]] = None
    输入需要改为

10. 任意 dict 构成的请求体

from typing import Optional, List, Set, Dict
@app.post("/index-weights/")
async def create_index_weights(weights: Dict[int, float]): 
                                # key 为 int, value 为浮点
    return weights

### 关于FastAPI和Vue3的学习教程与笔记 #### 使用FastAPI构建后端服务 为了创建一个基于FastAPI的Web应用,开发者可以利用其简洁而强大的特性来快速搭建RESTful API。下面是一个简单的例子,展示了如何设置带有跨源资源共享(CORS)中间件的基础应用程序[^4]。 ```python from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware app = FastAPI() # 添加CORS中间件允许所有来源访问API app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"] ) @app.get("/") async def read_root(): return {"message": "Hello World"} if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=8000) ``` 这段代码定义了一个基本的应用实例`app`并配置了必要的中间件以支持来自不同域的请求。通过装饰器`@app.get("/")`指定了根路径处理程序返回一条消息给客户端。 #### 利用Vue3设计前端界面 对于前端部分,则推荐采用现代JavaScript框架之一——Vue.js版本3来进行单页面应用程序(SPA)的设计工作。这里给出一段HTML模板以及相应的脚本片段用于初始化一个新的Vue项目: ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"/> <title>My App</title> <script src="https://unpkg.com/vue@next"></script> </head> <body> <div id="app">{{ message }}</div> <!-- 创建Vue实例 --> <script type="module"> import { createApp } from 'vue' createApp({ data() { return { message: 'Welcome to your new Vue application!' }; } }).mount('#app') </script> </body> </html> ``` 此示例中引入了最新版的Vue库文件,并通过ES模块语法动态加载它;接着声明了一个名为`app`的对象作为视图模型(View Model),其中包含了要绑定到DOM中的属性(`message`)及其初始值;最后调用了`.mount()`方法指定挂载点从而启动整个SPA生命周期。 #### 结合FastAPI与Vue3的最佳实践建议 当考虑将这两个工具链结合起来时,有几个方面值得注意: - **前后端分离架构**:保持清晰的服务层划分有助于团队协作分工明确; - **状态管理解决方案的选择**:针对复杂的状态逻辑可以选择Vuex或其他类似的库; - **HTTP通信协议**:通常会选用Axios发起异步请求并与服务器交互获取资源; - **安全性考量**:确保传输过程加密(HTTPS)、身份验证机制健全等措施保障信息安全[^1]。 #### 实战经验分享 根据实际案例分析,在学习过程中采取边做边学的方式往往能取得更好的效果。比如可以从模仿现有优秀作品入手,逐步理解各个知识点之间的联系,再尝试独立完成小型项目积累更多实践经验。此外,积极参与社区讨论也是不可或缺的一环,这不仅能够帮助解决遇到的具体难题,更能拓宽视野接触到最新的行业趋势和技术动向[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值