为什么我不能在Pydantic中创建Httpurl的独立对象?
from pydantic import BaseModel, Field, HttpUrl
from typing import Optional
class TestClass(BaseModel):
url:Optional[HttpUrl] = None
使用url =“ https://www.test.com创建对象testClass”工作。
在这里,导入的httpurl或basemodel是类。当我尝试创建httpurl对象独立时,它会在下面给出typeError。
from pydantic import HttpUrl
myurl = HttpUrl("https://www.test.com")
为什么不能像上面那样将其用于将字符串转换为HTTP对象。结果 错误如下:需要关键字,如果提供的话,则提供2个位置所需的2个位置3
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
upd 2023-10-30(感谢 christoph H. )
在Pydantic 2中,您应该使用typeadapter,因为PARSE_OBJ_AS被弃用。
(只有pydantic 1.x )您可以使用parse_obj_as方法。这样,依赖性将更少:
UPD 2023-10-30 (thanks Christoph H.)
In Pydantic 2 you should use a TypeAdapter, since parse_obj_as was deprecated.
(Only Pydantic 1.X) You can use parse_obj_as method. This way there will be fewer dependencies:
pydantic类型仅在用作
basemodel
衍生物内的类变量时有效。在引擎盖下,pydantic
的方法> anyurl
类,这对于外部使用不便。也许
urllib
库将为您提供方便?pydantic types are valid only when used as a class variables inside
BaseModel
derivatives.Under the hood, pydantic fires
validate
method ofAnyUrl
class which is inconvenient for external usage.Maybe
urllib
library will come handy for you?在Pydantic版本2中,您应该使用以下代码,因为PARSE_OBJ_AS已弃用:
In Pydantic version 2 you should use the following code, because parse_obj_as is deprecated: