from pydantic import BaseModel, Field, HttpUrl
from typing import Optional
class TestClass(BaseModel):
url:Optional[HttpUrl] = None
Creating object TestClass with url="https://www.test.com" works.
Here the imported HttpUrl or BaseModel are class. When I try to create httpurl object standalone it gives typeerror e.g. below.
from pydantic import HttpUrl
myurl = HttpUrl("https://www.test.com")
Why it cannot be used to convert string to http object like above. It results errors like: need keyword-only args if that is provided then 2 positional provided required 3
CodePudding user response:
pydantic types are valid only when used as a class variables inside BaseModel
derivatives.
Under the hood, pydantic fires validate
method of AnyUrl
class which is inconvenient for external usage.
Maybe urllib
library will come handy for you?
from urllib.parse import urlparse
myurl = urlparse("https://www.test.com")