gpt4 book ai didi

flask - 正确的 json 格式保存到 geoalchemy2 几何字段

转载 作者:行者123 更新时间:2023-12-05 05:26:46 24 4
gpt4 key购买 nike

我有一个这种格式的 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)

尝试使用分配有上述 json 值的 event.location 保存 event 对象失败并出现此错误

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

event.location 的正确格式是什么?

db.session.add(event)
db.session.commit()

正常工作?

最佳答案

我最终使用了以下代码片段:一种在加载/保存数据时使用 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

关于flask - 正确的 json 格式保存到 geoalchemy2 几何字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24034007/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com