79100325

Date: 2024-10-18 02:19:45
Score: 0.5
Natty:
Report link

You can achieve this by writing a functional validator like so:

from typing import Annotated

from pydantic import BaseModel, HttpUrl, AfterValidator

HttpStr = Annotated[HttpUrl, AfterValidator(str)]


class MyModel(BaseModel):
    url: HttpStr


m1 = MyModel(url="https://hello.com")
assert m1.url == "https://hello.com/"

m2 = MyModel(url="https://hello[.]com")  # raises ValidationError("Input should be a valid URL, invalid domain character")

In this example we leverage HttpUrl annotated type, and then add an AfterValidator to coerce the Url back into a string.

However, quickly shimming through the SQLAlchemy documentation it looks like this might be a common problem with a documented workaround. Potentially this might be more elegant approach to your specific problem?

A frequent need is to force the “string” version of a type, that is the one rendered in a CREATE TABLE statement or other SQL function like CAST, to be changed.

https://docs.sqlalchemy.org/en/20/core/custom_types.html#overriding-type-compilation

Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • Low reputation (1):
Posted by: Zac Scott