class Genders(str, Enum):
Male = 'male'
Female = 'female'
class ExtendItem(BaseModel):
a: str = ''
b: int = 0
c: float = 0.1
d: bool = False
class Config:
"""
在 Pydantic 模型中,Config 类用于配置模型的行为。你可以在这个类中设置多种属性来调整模型的解析、验证和序列化行为。以下是一些常用的 Config 类字段:
title: 用于为模型提供一个标题,通常用于生成的文档或模式中。
extra: 控制如何处理未在模型中声明的额外字段。可选值包括 ignore、allow、forbid。
arbitrary_types_allowed: 允许模型接受任意类型的字段,而不仅限于标准的 Pydantic 类型。
json_encoders: 为特定类型提供自定义的 JSON 编码器。
alias_generator: 生成别名的函数,用于字段名称,通常用于生成符合特定API规范的别名。
allow_population_by_field_name: 允许通过字段名称而不是别名来填充模型数据。
min_anystr_length: 字符串和字节类型字段的最小长度。
max_anystr_length: 字符串和字节类型字段的最大长度。
min_number_size: 数字类型字段的最小值。
max_number_size: 数字类型字段的最大值。
validate_assignment: 设置为 True 时,将在字段值被赋予新值后触发验证。
error_msg_templates: 自定义错误消息模板。
orm_mode: 允许模型与 ORM 模型兼容,通过允许使用非字典对象进行模型初始化。
use_enum_values: 当设置为 True 时,枚举字段将输出枚举成员的值而不是枚举成员本身。
anystr_strip_whitespace: 自动去除任何字符串或字节字段周围的空白。
schema_extra: 允许为 Pydantic 模型的 JSON Schema 添加额外的信息。
json_loads 和 json_dumps: 自定义 JSON 加载和转储函数。
keep_untouched: 保持某些类型在模型处理中不被修改,通常用于装饰器等高级用途。
"""
extra = "allow" # 允许额外字段
class Item1(BaseModel):
name: str = 'Bob'
description: str
price: float
tax: int
tags: list[str] = []
gender: Genders
flags: Literal['test1', 'test2']
class Config:
title = 'Item1'
extra = "allow" # 允许额外字段
test: Item1 = Item1(name = 'Boc',
description = 'test_desc',
price = 1.23,
tax = 123,
tags = ['tag_1', 'tag_2'],
gender = Genders.Male,
flags = 'test1',
extend = ExtendItem(a = 'a', b = 1, c = 0.1, d = True))
# 将 json string 转化为 model 对象
test = Item1.model_validate_json(test.model_dump_json(indent = 4))
# 将model对象打印成 json string
print(test.model_dump_json(indent = 4))
@app.get("/get_model")
async def get_model(items: Annotated[Item1, Query(description = 'GET 请求参数模型定义')]):
"""
GET请求不支持参数的嵌套
curl -X 'GET' \
'http://127.0.0.1:18081/get_model?name=Bob&description=desc_test&price=1.23&tax=123&tags=tag_1&tags=tag_2&gender=male&flags=test1' \
-H 'accept: application/json'
"""
print(items)
return {
"method": "GET",
"message": items
}
注意:查询参数不能使用嵌套的 model 对象。
通常,查询参数是扁平的键值对,而不是复杂的、嵌套的 JSON 对象。这意味着直接将一个嵌套的 Pydantic 模型用作查询参数并不直接支持。
class Item(BaseModel):
name: str
description: Optional[str] = None
@app.get("/items/")
async def read_items(json_str: str = Query(...)):
try:
item = parse_raw_as(Item, json_str)
return {"name": item.name, "description": item.description}
except Exception as e:
return {"error": str(e)}
class Item(BaseModel):
name: str
description: Optional[str] = None
def query_extractor(q: str = None):
# 这里可以添加解析逻辑,例如解析 JSON 字符串或处理多个相关查询参数
return Item(name=q, description="Sample")
@app.get("/items/")
async def read_items(item: Item = Depends(query_extractor)):
return {"name": item.name, "description": item.description}
class Item2(Item1):
extend: Annotated[ExtendItem, Field(description = 'a nested json object')]
class Config:
title = 'Item2'
extra = "forbid" # 不允许额外字段
@app.post("/post_model")
async def post_model(items: Annotated[Item2, Field(description = 'a nested parameter')]):
"""
POST请求支持参数的嵌套
curl -X POST "http://127.0.0.1:18081/post_model" \
-H "Content-Type: application/json" \
-d '{
"name": "Boc",
"description": "test_desc",
"price": 1.23,
"tax": 123,
"tags": [
"tag_1",
"tag_2"
],
"gender": "male",
"flags": "test1",
"extend": {
"a": "a",
"b": 1,
"c": 0.1,
"d": true
}
}'
"""
print(items)
return {
"method": "POST",
"message": items
}
@app.post("/post_model2/{item_id}")
async def post_model2(items: Annotated[Item2, Field(description = 'a nested parameter')],
q: Annotated[str, Query(description = '查询参数')],
item_id: Annotated[int, Path(description = '路径参数')]):
"""
POST请求与路径参数、查询参数的嵌套
curl -X 'POST' \
'http://127.0.0.1:18081/post_model2/1234?q=aaaaaaa' \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
"name": "Bob",
"description": "string",
"price": 0,
"tax": 0,
"tags": [],
"gender": "male",
"flags": "test1",
"extend": {
"a": "",
"b": 0,
"c": 0.1,
"d": false,
"additionalProp1": {}
}
}'
"""
print(items)
return {
"method": "POST",
"message": items,
'query': q,
'path_item_id': item_id
}
from __future__ import annotations
import uvicorn
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
description: str | None = None
price: float
tax: float | None = None
class User(BaseModel):
username: str
full_name: str | None = None
@app.post("/items/{item_id}")
async def post_item(item_id: int, item: Item, user: User):
"""
curl -X 'POST' \
'http://127.0.0.1:18081/items/123' \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
"item": {
"name": "aaaa",
"description": "aaaaa",
"price": 0,
"tax": 0
},
"user": {
"username": "bbbb",
"full_name": "cccc"
}
}'
"""
results = {"item_id": item_id, "item": item, "user": user}
return results
if __name__ == '__main__':
uvicorn.run(app, host = '127.0.0.1', port = 18081)
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有