pythonflask-sqlalchemyflask-adminspatialitegeoalchemy2

spatialite backend for geoalchemy2 in Python


I'm trying to SQLITE/spatialite with geoalchemy2. It seems to be possible according that link.

My problem comes I think from the custom engine.

What I have so far:

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()

When I start the script, I get the message below:

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)

Any idea how I could fix that ?


Solution

  • I had the same problem and it took a while to work it out. There are a bunch of layers (SQLAlchemy, Flask, SQLite, spatialite, Flask's SQLAlchemy extension, ....) working together. Hope this helps:

    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')