Giter Club home page Giter Club logo

Comments (4)

saschahofmann avatar saschahofmann commented on June 13, 2024 1

I managed to parse the DB data to a json response by defining this

from pydantic_geojson import FeatureModel
from geoalchemy2 import WKBElement
from geoalchemy2.shape import to_shape
from shapely import to_geojson
import json

class WKBToGeoJSON(FeatureModel):
    @classmethod
    def validate(cls, value):
        if not isinstance(value, WKBElement):
            raise TypeError("value must be a WKBElement object")
        shape = to_shape(value)
        if shape.type != "Point":
            raise TypeError("value must be a Point")
        return json.loads(to_geojson(shape))

And then defining my model using this Field

class Asset(BaseModel, table=True):
    name: Optional[str] = Field(default=None)
    description: Optional[str] = Field(default=None)
    location: WKBToGeoJSON = Field(
        default=None, sa_column=Column(Geometry("POINT", srid=4326))
    )

I havent tried it yet but I assume that the other way (geojson to sqlalchemy will fail).

@tiangolo is there some documentation on how to define the two way transformations for more exotic types?

from sqlmodel.

John-P avatar John-P commented on June 13, 2024 1

I'm not sure if this is the correct way to go about it, but I ended up doing this to test reading and writing geometry (using Postgres) as GeoJSON, and it appears to work well. If you are not using Postgres, you could replace the JSONB with regular SQLalchemy JSON.

If anyone knows of a better way to do this, please let me know.

import uuid
from typing import Literal, Optional

from fastapi import FastAPI, HTTPException

import geoalchemy2 as ga
from sqlmodel import Field, Session, SQLModel, create_engine, select
from sqlalchemy.dialects.postgresql import JSONB


engine = create_engine("postgresql://postgres:password@postgres/mydb")
app = FastAPI()


class GeoJSONGeometry(SQLModel):
    """A GeoJSON geometry fragment."""

    type: Literal["Point", "LineString", "Polygon"]
    coordinates: tuple[float, float] | list[tuple[float, float]] | list[list[tuple[float, float]]]


class Feature(SQLModel, table=True):
    id: Optional[uuid.UUID] = Field(
        default_factory=uuid.uuid4,
        primary_key=True,
        index=True,
        nullable=False,
    )
    geometry: bytes = Field(
        sa_type=ga.Geometry,
        nullable=False,
    )
    properties: Optional[dict] = Field(
        default=None,
        sa_type=JSONB,
        nullable=True,
    )


class FeatureCreate(SQLModel):
    geometry: GeoJSONGeometry = Field(
        default=None,
        sa_type=JSONB,
        nullable=False,
    )
    properties: Optional[dict]


class FeatureRead(FeatureCreate):
    id: uuid.UUID
    geometry: GeoJSONGeometry
    properties: Optional[dict]


@app.post("/features/", response_model=FeatureRead)
def create_feature(feature: FeatureCreate):
    with Session(engine) as session:
        db_feature = Feature(
            geometry=ga.functions.ST_SetSRID(
                ga.functions.ST_GeomFromGeoJSON(feature.geometry.model_dump_json()),
                0,  # PostGIS >3.0 ST_GeomFromGeoJSON sets the srid to 4326 by default
            ),
            properties=feature.properties,
        )
        session.add(db_feature)
        session.commit()
        session.refresh(db_feature)
        geojson = session.exec(
            select(ga.functions.ST_AsGeoJSON(db_feature.geometry))
        ).one()
    response = Feature(
        id=db_feature.id,
        geometry=GeoJSONGeometry.model_validate_json(geojson),
        properties=feature.properties,
    )
    return response


@app.get("/features/{feature_id}", response_model=FeatureRead)
def read_feature(feature_id: uuid.UUID):
    with Session(engine) as session:
        db_feature = session.get(Feature, feature_id)
        if db_feature is None:
            raise HTTPException(status_code=404, detail="Feature not found")
        geojson = session.exec(
            select(ga.functions.ST_AsGeoJSON(db_feature.geometry))
        ).one()
    response = FeatureRead(
        id=db_feature.id,
        geometry=GeoJSONGeometry.model_validate_json(geojson),
        properties=db_feature.properties,
    )
    return response

from sqlmodel.

saschahofmann avatar saschahofmann commented on June 13, 2024

Any success with this? I also tried to find whether pydantic has some capabilities around geospatial data. The closest I have found is https://pypi.org/project/geojson-pydantic/

from sqlmodel.

John-P avatar John-P commented on June 13, 2024

I would also love to know how to handle geoJSON input/output for Geometry in a Postgres/Spatialite database backend. It appears to work just fine for WKT but it would be great to be able to validate/dump geoJSON. Two killer features for me are supporting geometry and JSON (e.g. for a JSONB column).

from sqlmodel.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.