1

I've got a bunch of GIS tables in my model that I created in flaskSQLAlchemy. Each of these models has a 'geom' field which is a WKB object. Which need to be JSON serialized into WKT or geojson, So that The API GET call would work.

I tried to use geoalchemy2 functions, but I'm stuck. I use a flask marshmallow/marshmallow-sqlalchemy combo, and I tried something like the following, with no luck.

from geoalchemy2 import functions
from marshmallow import fields

class WKTSerializationField(fields.Field):
def _serialize(self, value, attr, obj):
    if value is None:
        return value
    else:
        if type(value).__name__ == 'WKBElement':
            return functions.ST_AsEWKT(value)
        else:
            return None



class GISModelTableSchema(ma.ModelSchema):
    class Meta:
       model = GISModelTable
    geom = WKTSerializationField(attribute="geom")

Please provide a code example if you can, how to serialize/deserialize a field in marshmallow alchemy. Or any answer is welcomed at this point.

Krzysztof Madej
  • 32,704
  • 10
  • 78
  • 107
ISONecroMAn
  • 1,460
  • 2
  • 16
  • 23

1 Answers1

0

Try to use marshmallow-sqlalchemy 'fields.Method()' and in the method use another method 'to_shape' from geoalchemy2.shape package. This will help you with serialization issue.

    #!schemas.py
    from marshmallow import fields
    from marshmallow_sqlalchemy import ModelSchema
    from geoalchemy2.shape import to_shape
    from .models import YourModel
    
    class YourModelSchema(ModelSchema):
        your_geom_field = fields.Method("geom_to_dict")
        
        @staticmethod
        def geom_to_dict(obj):
            point = to_shape(obj.your_geom_field)
            return { 
                      lat: point.y,
                      lon: point.x
                   }
    
        class Meta:
              model = YourModel
              exclude = ("your_geom_field")

this migh help you with serialization, for desirialization you may read more detailed in geoalchemy2 api reference

Try to code all required fields by yourself, you may get more specific serialization in a form you want

James Nur
  • 23
  • 4