attributeError:键入对象' filepath'没有属性' _flavour' [pydantic]
我使用pydantic进行数据验证。我想做的是创建一个具有可选字段的模型,该模型指向现有文件。问题是,下面的代码不起作用。
from pydantic import BaseModel, FilePath
class Model(BaseModel):
# Assuming I have file.txt in working directory.
file: FilePath = FilePath('./file.txt')
model = Model()
Traceback (most recent call last):
File "C:\Users\mikheenkov\temp.py", line 4, in <module>
class Model(BaseModel):
File "C:\Users\mikheenkov\temp.py", line 5, in Model
ssh_server_host_key: FilePath = FilePath('.')
File "C:\Program Files\Python39\lib\pathlib.py", line 1082, in __new__
self = cls._from_parts(args, init=False)
File "C:\Program Files\Python39\lib\pathlib.py", line 707, in _from_parts
drv, root, parts = self._parse_args(args)
File "C:\Program Files\Python39\lib\pathlib.py", line 700, in _parse_args
return cls._flavour.parse_parts(parts)
AttributeError: type object 'FilePath' has no attribute '_flavour'
有解决方法吗?
编辑:Python版本为3.9.8,Pydantic版本为1.9.0。
I use pydantic for data validation. What I want to do is to create a model with an optional field, which points to the existing file. The problem is, the code below does not work.
from pydantic import BaseModel, FilePath
class Model(BaseModel):
# Assuming I have file.txt in working directory.
file: FilePath = FilePath('./file.txt')
model = Model()
Traceback (most recent call last):
File "C:\Users\mikheenkov\temp.py", line 4, in <module>
class Model(BaseModel):
File "C:\Users\mikheenkov\temp.py", line 5, in Model
ssh_server_host_key: FilePath = FilePath('.')
File "C:\Program Files\Python39\lib\pathlib.py", line 1082, in __new__
self = cls._from_parts(args, init=False)
File "C:\Program Files\Python39\lib\pathlib.py", line 707, in _from_parts
drv, root, parts = self._parse_args(args)
File "C:\Program Files\Python39\lib\pathlib.py", line 700, in _parse_args
return cls._flavour.parse_parts(parts)
AttributeError: type object 'FilePath' has no attribute '_flavour'
Is there a workaround?
EDIT: Python version is 3.9.8 and pydantic version is 1.9.0.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您需要将默认值作为字符串提供:
edit:pydantic似乎没有检查默认值是存在的文件:
但是它确实检查了是否提供:
edit2:这是预期的行为,如果您想要此检查,可以使用
config.validate_all = true = true :
I think that you need to provide the default value as a string:
EDIT: pydantic does not seem to check that the default value is a file that exists:
But it does check if you supply it:
EDIT2: This is the intended behavior, and if you want this check you can use
Config.validate_all = True
: