Replies: 2 comments 1 reply
-
Any idea ? Does anyone do type validation on IP address like that ? |
Beta Was this translation helpful? Give feedback.
-
FYI the issue encountered with the insertion is not directly linked to SQLModel but rather to SQLAlchemy dialect which can't convert What could be done to fix the issue is creating a custom SQLAlchemy type which insert the pydantic from typing import Optional
from sqlmodel import AutoString, Field, SQLModel
from pydantic import IPvAnyAddress
class IPvAnyAddressType(AutoString):
def process_bind_param(self, value, dialect) -> Optional[str]:
if value is None:
return None
if isinstance(value, str):
# Test if value is a valid IP address to avoid process result value failling
try:
IPvAnyAddress(value)
except ValueError as e:
raise ValueError(f"{value} is not a valid IP address") from e
return str(value)
def process_result_value(self, value, dialect) -> Optional[IPvAnyAddress]:
if value is None:
return None
return IPvAnyAddress(value)
class DeviceBase(SQLModel, table=True):
# ...
management_ip: IPvAnyAddress = Field(sa_type=IPvAnyAddressType)
# ... This approach will allow you to use the |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
First Check
Commit to Help
Example Code
Description
My goal was to have data validation for IP Addresses on my project:
At first I just had
management_ip: IPvAnyAddress = Field()
to add the field but it led to the errorValueError: <class 'pydantic.networks.IPvAnyAddress'> has no matching SQLAlchemy type
Then I found the following discussion ValueError: <class 'pydantic.networks.EmailStr'> has no matching SQLAlchemy type #730 which was on a similar topic and tried to apply the two proposed solutions
The first solution was to use sa_type=AutoString leading to this line of code :
management_ip: IPvAnyAddress = Field(sa_type=AutoString)
However it led to an unexpected error when trying to post one of these objects into my database :
sqlalchemy.exc.DBAPIError: (sqlalchemy.dialects.postgresql.asyncpg.Error) <class 'asyncpg.exceptions.DataError'>: invalid input for query argument $2: IPv4Address('12.34.56.78') (expected str, got IPv4Address)
The second solution was to use sa_column=Column(String) leading to this line of code :
management_ip: IPvAnyAddress = Field(sa_column=Column(String))
However it led to the same exact error when trying to post data.
It looks like the solutions aren't being properly applied looking at the logs of the insertion in the SQL database :
Do you have any idea about that ?
Does anyone manage to use successfully this feature to do type validation ?
Operating System
Linux
Operating System Details
Ubuntu 22.04.4 LTS
SQLModel Version
0.0.16
Python Version
Python 3.11.4
Additional Context
Relevant dependencies :
Beta Was this translation helpful? Give feedback.
All reactions