| 1 |
"""pydantic models for GeoJSON Feature objects.""" |
| 2 |
|
| 3 |
from typing import Any, Dict, Generic, Iterator, List, Literal, Optional, TypeVar, Union |
| 4 |
|
| 5 |
from pydantic import ( |
| 6 |
BaseModel, |
| 7 |
Field, |
| 8 |
StrictFloat, |
| 9 |
StrictInt, |
| 10 |
StrictStr, |
| 11 |
field_validator, |
| 12 |
) |
| 13 |
from typing_extensions import Annotated |
| 14 |
|
| 15 |
from geojson_pydantic.base import _GeoJsonBase |
| 16 |
from geojson_pydantic.geometries import Geometry |
| 17 |
|
| 18 |
Props = TypeVar("Props", bound=Union[Dict[str, Any], BaseModel]) |
| 19 |
Geom = TypeVar("Geom", bound=Geometry) |
| 20 |
|
| 21 |
|
| 22 |
class Feature(_GeoJsonBase, Generic[Geom, Props]): |
| 23 |
"""Feature Model""" |
| 24 |
|
| 25 |
type: Literal["Feature"] |
| 26 |
geometry: Union[Geom, None] = Field(...) |
| 27 |
properties: Union[Props, None] = Field(...) |
| 28 |
id: Optional[ |
| 29 |
Union[StrictInt, Annotated[StrictFloat, Field(allow_inf_nan=False)], StrictStr] |
| 30 |
] = None |
| 31 |
|
| 32 |
__geojson_exclude_if_none__ = {"bbox", "id"} |
| 33 |
|
| 34 |
@field_validator("geometry", mode="before") |
| 35 |
def set_geometry(cls, geometry: Any) -> Any: |
| 36 |
"""set geometry from geo interface or input""" |
| 37 |
if hasattr(geometry, "__geo_interface__"): |
| 38 |
return geometry.__geo_interface__ |
| 39 |
|
| 40 |
return geometry |
| 41 |
|
| 42 |
|
| 43 |
Feat = TypeVar("Feat", bound=Feature) |
| 44 |
|
| 45 |
|
| 46 |
class FeatureCollection(_GeoJsonBase, Generic[Feat]): |
| 47 |
"""FeatureCollection Model""" |
| 48 |
|
| 49 |
type: Literal["FeatureCollection"] |
| 50 |
features: List[Feat] |
| 51 |
|
| 52 |
def iter(self) -> Iterator[Feat]: |
| 53 |
"""iterate over features""" |
| 54 |
return iter(self.features) |
| 55 |
|
| 56 |
@property |
| 57 |
def length(self) -> int: |
| 58 |
"""return features length""" |
| 59 |
return len(self.features) |