为什么 pydantic 不验证 Foo 对象列表的参数,但当参数是基本类型列表时抛出 ValidationError ?
我可以强制执行复杂类型的验证吗?
验证不起作用:
from typing import List
from pydantic import BaseModel
class Foo(BaseModel):
kind: str = "foo"
class Bar(BaseModel):
kind: str = "bar"
class Spam(BaseModel):
foos: List[Foo]
spam = Spam(foos=[Bar()])
print(spam.dict())
>>> {'foos': [{'kind': 'bar'}]}
Run Code Online (Sandbox Code Playgroud)
验证工作:
class Spam(BaseModel):
foos: List[int]
spam = Spam(foos=[Bar()])
print(spam.dict())
pydantic.error_wrappers.ValidationError: 1 validation error for Spam
foos -> 0
value is not a valid integer (type=type_error.integer)
Run Code Online (Sandbox Code Playgroud) 我正在使用 FastAPI 构建数据 API。我希望客户发布 2 个包含 24 个浮点数的列表,稍后我会将其保存到数据库中。
当我尝试创建 Pydantic 模型时:
from pydantic import BaseModel
class Prices(BaseModel):
buying_price: list(float)=[]
selling_price: list(float)=[]
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
File "c:/Users/Amin y Lubna/FastAPI-InfluxDB/test.py", line 3, in <module>
class Prices(BaseModel):
File "c:/Users/Amin y Lubna/FastAPI-InfluxDB/test.py", line 4, in Prices
buying_price: list(float)=[]
TypeError: 'type' object is not iterable
Run Code Online (Sandbox Code Playgroud)
尽管该错误是不言自明的,但我不明白。
然后,查看文档,我发现了以下方法:
from pydantic import BaseModel
from typing import List
class Prices(BaseModel):
buying_price: List(float)=[]
selling_price: List(float)=[]
Run Code Online (Sandbox Code Playgroud)
但我收到以下错误。
File "c:/Users/Amin y Lubna/FastAPI-InfluxDB/test.py", line 4, in <module>
class Prices(BaseModel):
File "c:/Users/Amin y Lubna/FastAPI-InfluxDB/test.py", line …Run Code Online (Sandbox Code Playgroud) 我有一个接受 get 和 post 请求的 Flask 视图,并使用 Pydantic 使用 Flask-pydantic 进行请求正文验证。它适用于 post 请求,但在 get 请求时,它会返回 415 错误并显示此消息 - {"detail":"请求中不支持媒体类型 ''。需要 'application/json'。"}
@bp.route('/login', methods=('GET', 'POST',))
@validate()
def login(body: UserLoginSchema):
if request.method == 'POST':
existing_user = UserListSchema.from_orm(
db_session.query(UserModel.id, UserModel.email, UserModel.first_name, UserModel.last_name,
UserModel.is_admin, UserModel.is_verified, UserModel.password)
.filter_by(email=body.email, is_active=True).first()
)
if existing_user:
if check_password_hash(existing_user.password, body.password):
session.clear()
session['user'] = str(existing_user.json())
return redirect(url_for('index'))
flash('Invalid username or password')
return render_template('auth/login.html')
Run Code Online (Sandbox Code Playgroud)
我尝试将函数中的查询参数设置为空字符串或无,但没有帮助。
所以,我有一个django模型,比如说,它的字段划分如下:
class ModelA(models.Model):
f1 = models.CharField(max_length=127)
f2 = models.CharField(max_length=127)
Run Code Online (Sandbox Code Playgroud)
我想创建一个 pydantic 类,其字段类型包含这些模型的列表。考虑以下示例:
class TestPydanticClass(BaseModel):
model_a_values: List[ModelA]
f4: int
Run Code Online (Sandbox Code Playgroud)
当我尝试创建TestPydanticClass对象时,它抛出以下错误:
RuntimeError: no validator found see `arbitrary_types_allowed` in Config
Run Code Online (Sandbox Code Playgroud)
基于此,我在模型的类arbitrary_types_allowed下添加为 True Config,但它仍然抛出错误。有人可以建议更好的方法来实现这一目标吗?
如何定义 json 属性到属性名称不同的 pydantic 模型之间的映射?IE:
# I want to parse thumbnailUrl into thumbnail
class ChatMessageAttachment(BaseModel):
id: str
thumbnail: Optional["str"] = None
external_data = {"id": "123", "thumbnailUrl": "www.google.es"}
chat_message = ChatMessageAttachment(**external_data)
print(chat_message) # >>>id='123' thumbnail=None
Run Code Online (Sandbox Code Playgroud) pydantic中有一个DocumentSchema用FastApi编写的类的嵌套规则如下:
class DocumentSchema(BaseModel):
clientName: str
transactionId: str
documentList: List[SingleDocumentSchema]
Run Code Online (Sandbox Code Playgroud)
和
class SingleDocumentSchema(BaseModel):
documentInfo: DocumentInfoSchema
articleList: List[DocumentArticleSchema]
Run Code Online (Sandbox Code Playgroud)
和
class DocumentInfoSchema(BaseModel):
title: str
type: str
referenceId: int
batchNoList: Optional[List]
otherData: Optional[Json]
Run Code Online (Sandbox Code Playgroud)
和
class DocumentArticleSchema(BaseModel):
type: str
value: int
accountType: Optional[AccountTypeEnums]
accountId: Optional[int]
otherData: Optional[Json]
Run Code Online (Sandbox Code Playgroud)
这是从 Kafka 接收消息并处理它的 python 代码片段:
def process(self) -> bool:
try:
DocumentSchema(
**json.loads(self._message)
)
return self._process()
except ValidationError as e:
raise UnprocessableEntityException(e, self._topic)
except ValueError as e:
raise UnprocessableEntityException(e, self._topic)
except Exception as e:
raise UnprocessableEntityException(e, self._topic) …Run Code Online (Sandbox Code Playgroud) 我想根据用户输入对对象列表进行排序,其中我允许按 ASC 顺序对某些列进行排序,而按 DESC 顺序对其他列进行排序(该字段是字符串/数字 - 但对于数字没有问题)。
示例类和对象列表如下所示:
from pydantic import BaseModel
class Person(BaseModel):
firstname: str
lastname: str
weight: float
people = [
Person(firstname="John", lastname="Snow", weight=100.1),
Person(firstname="Matthew", lastname="Smith", weight=98.7),
# And more...
]
Run Code Online (Sandbox Code Playgroud)
所以问题是我想按名字 ASC、姓氏 DESC (以及其他字段也是 DESC 或 ASC)对对象进行排序。
我试着这样做people.sort(lambda person: (-person.firstname, person.lastname))
但我得到了TypeError: bad operand type for unary -: 'str'。
我正在尝试创建一个包含 pydantic/pydantic_core (Lambda python 3.11,x86_64)的 lambda 层,但出现以下错误:"Unable to import module 'reddit_lambda': No module named 'pydantic_core._pydantic_core'"
作为上下文,我将其安装在 Windows x64 计算机上。
从这里、这里和这里阅读有关内容,似乎 pip 安装 pydantic 是为了不兼容的体系结构(win_amd64)。
安装日志:
Using cached pydantic-2.4.2-py3-none-any.whl (395 kB)
Using cached pydantic_core-2.10.1-cp311-none-win_amd64.whl (2.0 MB)
Run Code Online (Sandbox Code Playgroud)
我的问题:有没有办法强制 pip 将软件包安装到 powershell 中特定架构的目录中?
我在这里看到了一个旧的讨论,这对于 Linux 来说是可能的,但不知道如何在 powershell 上做到这一点。
仅供参考:我还尝试从二进制文件中添加 pydantic_core (尝试过 pydantic_core-2.10.1-pp39-pypy39_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl和 pydantic_core-2.10.1-pp38-pypy38_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl),但我对选择哪个版本有点困惑?
我目前正在学习 fastAPI 教程,我的环境设置了 black、flake8、bandit 和 mypy。本教程中的所有内容都运行良好,但我一直不得不 # type: ignore things 让 mypy 合作。
class Item(BaseModel):
name: str
description: str = None
price: float
tax: float = None
@app.post("/items/")
async def create_items(item: Item) -> Item:
return item
Run Code Online (Sandbox Code Playgroud)
Mypy然后错误:
? mypy main.py [14:34:08]
main.py:9: error: Incompatible types in assignment (expression has type "None", variable has type "str")
main.py:11: error: Incompatible types in assignment (expression has type "None", variable has type "float")
Run Code Online (Sandbox Code Playgroud)
我可以 # type: ignore,但随后我丢失了编辑器中的类型提示和验证。我是否遗漏了一些明显的东西,还是应该为 FastAPI 项目禁用 mypy?
我有一个像这样的 BaseModel
from pydantic import BaseModel
class TestModel(BaseModel):
id: int
names: str = None
Run Code Online (Sandbox Code Playgroud)
虽然我验证了一些这样的数据
TestModel(id=123).dict()
Run Code Online (Sandbox Code Playgroud)
I got result
{'id': 123, 'name': None}
But what I expect is:
{'id': 123}
Question: Is there a method to delete empty field? Thanks!
pydantic ×10
python ×7
fastapi ×3
aws-lambda ×1
django ×1
flask ×1
json ×1
list ×1
mypy ×1
powershell ×1
python-3.x ×1
validation ×1