Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/validate json update #73

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 33 additions & 11 deletions geojson_pydantic/geometries.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@
from pydantic import BaseModel, Field, ValidationError, validator
from pydantic.error_wrappers import ErrorWrapper

try:
from functools import singledispatchmethod
except ImportError:
from singledispatchmethod import singledispatchmethod


from geojson_pydantic.types import (
LinearRing,
LineStringCoords,
Expand All @@ -28,17 +34,33 @@ class _GeometryBase(BaseModel, abc.ABC):
def __geo_interface__(self):
return self.dict()

class Config:
keep_untouched = (singledispatchmethod,)

@singledispatchmethod
@staticmethod
def validate(value):
"""Validate geometry object from unexpected type."""
raise ValueError

@validate.register
@classmethod
def validate(cls, value):
try:
value = json.loads(value)
except TypeError:
try:
return cls(**value.dict())
except (AttributeError, ValidationError):
pass
def _(cls, value: dict):
"""Validate geometry object from dictionary."""
value = cls(**value)
return value

return cls(**value)
@validate.register
@classmethod
def _(cls, value: str):
"""Validate geometry object from json-formatted string."""
return cls.validate(json.loads(value))

@validate.register
@classmethod
def _(cls, value: BaseModel):
"""Validate geometry object from Pydantic BaseModel object."""
return cls.validate(value.dict())

@property
@abc.abstractmethod
Expand Down Expand Up @@ -128,7 +150,7 @@ def _wkt_coordinates(self) -> str:
class LinearRingGeom(LineString):
"""LinearRing model."""

@validator("coordinates")
@validator("coordinates", allow_reuse=True)
def check_closure(cls, values):
"""Validate that LinearRing is closed (first and last coordinate are the same)."""
if values[-1] != values[0]:
Expand All @@ -143,7 +165,7 @@ class Polygon(_GeometryBase):
type: str = Field("Polygon", const=True)
coordinates: PolygonCoords

@validator("coordinates")
@validator("coordinates", allow_reuse=True)
def check_closure(cls, polygon):
"""Validate that Polygon is closed (first and last coordinate are the same)."""
if any([ring[-1] != ring[0] for ring in polygon]):
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ classifiers = [
"Typing :: Typed",
]
dynamic = ["version"]
dependencies = ["pydantic"]
dependencies = ["pydantic", "singledispatchmethod"]

[project.optional-dependencies]
test = ["pytest", "pytest-cov", "shapely"]
Expand Down