Debian Codegraph @

geojson_pydantic/base.py

raw
1 """pydantic BaseModel for GeoJSON objects."""
2
3 from __future__ import annotations
4
5 import warnings
6 from typing import Any, Dict, List, Optional, Set
7
8 from pydantic import BaseModel, SerializationInfo, field_validator, model_serializer
9
10 from geojson_pydantic.types import BBox
11
12
13 class _GeoJsonBase(BaseModel):
14 bbox: Optional[BBox] = None
15
16 # These fields will not be included when serializing in json mode
17 # `.model_dump_json()` or `.model_dump(mode="json")`
18 __geojson_exclude_if_none__: Set[str] = {"bbox"}
19
20 @property
21 def __geo_interface__(self) -> Dict[str, Any]:
22 """GeoJSON-like protocol for geo-spatial (GIS) vector data.
23
24 ref: https://gist.github.com/sgillies/2217756#__geo_interface
25 """
26 return self.model_dump(mode="json")
27
28 @field_validator("bbox")
29 def validate_bbox(cls, bbox: Optional[BBox]) -> Optional[BBox]:
30 """Validate BBox values are ordered correctly."""
31 # If bbox is None, there is nothing to validate.
32 if bbox is None:
33 return None
34
35 # A list to store any errors found so we can raise them all at once.
36 errors: List[str] = []
37
38 # Determine where the second position starts. 2 for 2D, 3 for 3D.
39 offset = len(bbox) // 2
40
41 # Check X
42 if bbox[0] > bbox[offset]:
43 warnings.warn(
44 f"BBOX crossing the Antimeridian line, Min X ({bbox[0]}) > Max X ({bbox[offset]}).",
45 UserWarning,
46 stacklevel=1,
47 )
48
49 # Check Y
50 if bbox[1] > bbox[1 + offset]:
51 errors.append(f"Min Y ({bbox[1]}) must be <= Max Y ({bbox[1 + offset]}).")
52
53 # If 3D, check Z values.
54 if offset > 2 and bbox[2] > bbox[2 + offset]:
55 errors.append(f"Min Z ({bbox[2]}) must be <= Max Z ({bbox[2 + offset]}).")
56
57 # Raise any errors found.
58 if errors:
59 raise ValueError("Invalid BBox. Error(s): " + " ".join(errors))
60
61 return bbox
62
63 # This return is untyped due to a workaround until this issue is resolved:
64 # https://github.com/tiangolo/fastapi/discussions/10661
65 @model_serializer(when_used="always", mode="wrap")
66 def clean_model(self, serializer: Any, info: SerializationInfo): # type: ignore [no-untyped-def]
67 """Custom Model serializer to match the GeoJSON specification.
68
69 Used to remove fields which are optional but cannot be null values.
70 """
71 # This seems like the best way to have the least amount of unexpected consequences.
72 # We want to avoid forcing values in `exclude_none` or `exclude_unset` which could
73 # cause issues or unexpected behavior for downstream users.
74 # ref: https://github.com/pydantic/pydantic/issues/6575
75 data: Dict[str, Any] = serializer(self)
76
77 # Only remove fields when in JSON mode.
78 if info.mode_is_json():
79 for field in self.__geojson_exclude_if_none__:
80 if field in data and data[field] is None:
81 del data[field]
82
83 return data