更正json格式以保存到geoalchemy2几何字段中

时间:2014-06-04 09:41:27

标签: flask geoalchemy2

我有一个这种格式的json:

{

     "type":"Feature",
     "properties":{},
     "geometry":{
          "type":"Point",
          "coordinates":[6.74285888671875,-3.6778915094650726]
     }
}

如下所示:flask-geoalchemy2定义的字段: -

from app import db
from app.mixins import TimestampMixin
from geoalchemy2 import Geometry

class Event(db.Model, TimestampMixin):
    __tablename__ = 'events'

    id = db.Column(db.BigInteger, primary_key=True)
    title = db.Column(db.Unicode(255))
    start = db.Column(db.DateTime(timezone=True))
    location = db.Column(Geometry(geometry_type='POINT', srid=4326))
    is_active = db.Column(db.Boolean(), default=False)

    def __repr__(self):
        return '<Event %r %r>' % (self.id, self.title)

尝试保存event对象,并为event.location分配上述json值失败,并显示此错误

DataError: (DataError) Geometry SRID (0) does not match column SRID (4326)

为什么格式event.location必须正确
db.session.add(event)
db.session.commit() 

正常工作?

2 个答案:

答案 0 :(得分:0)

我处理geojson的方式出错了。我需要明确说明geojson必须符合的srid

这是解决方案: -

def process_formdata(self, valuelist):
    """ Convert GeoJSON to DB object """
    if valuelist:
        geo_ob = geojson.loads(valuelist[0])
        # Convert the Feature into a Shapely geometry and then to GeoAlchemy2 object
        # We could do something with the properties of the Feature here...
        self.data = from_shape(asShape(geo_ob.geometry), srid=4326)
    else:
        self.data = None

答案 1 :(得分:0)

我最终使用了以下代码段:一种在加载/保存数据时使用GeoJSON值的列类型:


class GeometryJSON(Geometry):
    """ Geometry, as JSON

    The original Geometry class uses strings and transforms them using PostGIS functions:
        ST_GeomFromEWKT('SRID=4269;POINT(-71.064544 42.28787)');

    This class replaces the function with nice GeoJSON objects:
        {"type": "Point", "coordinates": [1, 1]}
    """
    from_text = 'ST_GeomFromGeoJSON'
    as_binary = 'ST_AsGeoJSON'
    ElementType = dict

    def result_processor(self, dialect, coltype):
        # Postgres will give us JSON, thanks to `ST_AsGeoJSON()`. We just return it.
        def process(value):
            return value
        return process

    def bind_expression(self, bindvalue):
        return func.ST_SetSRID(super().bind_expression(bindvalue), self.srid)

    def bind_processor(self, dialect):
        # Dump incoming values as JSON
        def process(bindvalue):
            if bindvalue is None:
                return None
            else:
                return json.dumps(bindvalue)
        return process

    @property
    def python_type(self):
        return dict