Python 中 geoalchemy2 的 spatialite 后端

spatialite backend for geoalchemy2 in Python

我正在尝试 SQLITE/spatialite 和 geoalchemy2。根据link.

似乎是可以的

我认为我的问题出在自定义引擎上。

我目前拥有的:

from flask_sqlalchemy import SQLAlchemy
from geoalchemy2 import Geometry
#and other imports...

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////Users/cricket/Documents/peas project/open-peas/localapp/test.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_ECHO'] = True

db = SQLAlchemy(app)

class Polygon(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True)
    point = db.Column(Geometry("POLYGON"))

@app.before_first_request
def init_request():
    db.create_all()

当我启动脚本时,我收到以下消息:

cursor.execute(statement, parameters)
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) near "POLYGON": syntax error [SQL: '\nCREATE TABLE polygon (\n\tid INTEGER NOT NULL, \n\tname VARCHAR(64), \n\tpoint geometry(POLYGON,-1), \n\tPRIMARY KEY (id), \n\tUNIQUE (name)\n)\n\n'] (Background on this error at: http://sqlalche.me/e/e3q8)

知道如何解决这个问题吗?

我遇到了同样的问题,花了一段时间才解决。有很多层(SQLAlchemy、Flask、SQLite、spatialite、Flask 的 SQLAlchemy 扩展......)一起工作。希望这会有所帮助:

from sqlalchemy import event

db = SQLAlchemy(app)

@event.listens_for(db.engine, "connect")
def load_spatialite(dbapi_conn, connection_record):
  # From https://geoalchemy-2.readthedocs.io/en/latest/spatialite_tutorial.html
  dbapi_conn.enable_load_extension(True)
  dbapi_conn.load_extension('/usr/lib/x86_64-linux-gnu/mod_spatialite.so')

在同样的问题上苦苦挣扎,即使答案被接受,我最终意识到 Geometry() 构造函数的 management 参数丢失了,如 here.[=14 所解释的=]

以下内容应该向 DB API 发送正确的 sql 命令:

class Polygon(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True)
    point = db.Column(Geometry("POLYGON", management = True))