-
Notifications
You must be signed in to change notification settings - Fork 35
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
Create a base model and generic serialization. #144
Merged
eseglem
merged 3 commits into
developmentseed:CustomSerializer
from
eseglem:CustomSerializer
Jul 21, 2023
+179
−141
Merged
Changes from 1 commit
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next
Next commit
Create a base model and generic serialization.
- Loading branch information
commit 58db3434916a2816948dc39d3fb16da9bbe6f0a3
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,68 @@ | ||
"""pydantic BaseModel for GeoJSON objects.""" | ||
from __future__ import annotations | ||
|
||
from typing import Any, Dict, List, Optional, Set | ||
|
||
from pydantic import BaseModel, SerializationInfo, field_validator, model_serializer | ||
|
||
from geojson_pydantic.types import BBox | ||
|
||
|
||
class _GeoJsonBase(BaseModel): | ||
bbox: Optional[BBox] = None | ||
|
||
# These fields will not be included when serializing in json mode | ||
# `.model_dump_json()` or `.model_dump(mode="json")` | ||
__exclude_if_none__: Set[str] = {"bbox"} | ||
|
||
@property | ||
def __geo_interface__(self) -> Dict[str, Any]: | ||
"""GeoJSON-like protocol for geo-spatial (GIS) vector data. | ||
|
||
ref: https://gist.github.com/sgillies/2217756#__geo_interface | ||
""" | ||
return self.model_dump(mode="json") | ||
|
||
@field_validator("bbox") | ||
def validate_bbox(cls, bbox: Optional[BBox]) -> Optional[BBox]: | ||
"""Validate BBox values are ordered correctly.""" | ||
# If bbox is None, there is nothing to validate. | ||
if bbox is None: | ||
return None | ||
|
||
# A list to store any errors found so we can raise them all at once. | ||
errors: List[str] = [] | ||
|
||
# Determine where the second position starts. 2 for 2D, 3 for 3D. | ||
offset = len(bbox) // 2 | ||
|
||
# Check X | ||
if bbox[0] > bbox[offset]: | ||
errors.append(f"Min X ({bbox[0]}) must be <= Max X ({bbox[offset]}).") | ||
# Check Y | ||
if bbox[1] > bbox[1 + offset]: | ||
errors.append(f"Min Y ({bbox[1]}) must be <= Max Y ({bbox[1 + offset]}).") | ||
# If 3D, check Z values. | ||
if offset > 2 and bbox[2] > bbox[2 + offset]: | ||
errors.append(f"Min Z ({bbox[2]}) must be <= Max Z ({bbox[2 + offset]}).") | ||
|
||
# Raise any errors found. | ||
if errors: | ||
raise ValueError("Invalid BBox. Error(s): " + " ".join(errors)) | ||
|
||
return bbox | ||
|
||
@model_serializer(when_used="json", mode="wrap") | ||
def clean_model(self, serializer: Any, _info: SerializationInfo) -> Dict[str, Any]: | ||
"""Custom Model serializer to match the GeoJSON specification. | ||
|
||
Used to remove fields which are optional but cannot be null values. | ||
""" | ||
# This seems like the best way to have the least amount of unexpected consequences. | ||
# We want to avoid forcing values in `exclude_none` or `exclude_unset` which could | ||
# cause issues or unexpected behavior for downstream users. | ||
data: Dict[str, Any] = serializer(self) | ||
for field in self.__exclude_if_none__: | ||
if field in data and data[field] is None: | ||
del data[field] | ||
return data |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🤯
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yeah, this was a nice little fix here when I realized the old
exclude_unset=True
was potentially problematic. Not so much on the Geometry types, but on Feature / FeatureCollection it could affect Properties if someone has defaults set in that model.