pythonmarshmallowgeoalchemy2

Return Marshmallow Raw data for Geoalchemy2


I have the following SQLAlchemy model.

class LocationModel(db.Model, BaseModel):
    """
    Location Model
    """

    __tablename__ = 'location'

    geolocation = db.Column(ga.Geometry('POINT', dimension=2, srid=4326))

    def __init__(self, data):
        self.geolocation      = self.__format_geolocation()

        # variables for other functions
        self.result_quantity = data.get('result_quantity')

    def save_event_local(self):
        db.session.add(self)
        db.session.flush()

    def __format_geolocation(self):
        if self.latitude or self.longitude == None:
            return None
        else:
            return 'SRID=4326;POINT({} {})'.format(self.longitude, self.latitude)

I would like to return the raw data like so (marshmallow):

class LocationSchema(Schema):
    """
    Location Schema
    """
    geolocation = fields.Raw()

Unfortunately I get the following error:

TypeError: Object of type WKBElement is not JSON serializable

I am not sure why this is happening.

Any idea how I can either serialize the deserialize Geoalchemy2 object or possibly just return the raw data so it can be used in the front end.

Thanks,


Solution

  • I was finally able to solve my problem by doing the following:

    from geoalchemy2 import functions
    
    functions.ST_AsGeoJSON(LocationModel.geolocation).label('geolocation'))
    

    This gave me an output of:

    {
      "geolocation": "{\"type\":\"Point\",\"coordinates\":[-70.77919769,-27.26119995]}"
    }