Search code examples
pythonpostgresqlflaskalembicgeoalchemy2

Alembic migration for GeoAlchemy2 raises NameError: name 'geoalchemy2' is not defined


I've decided to write a small webapp using Flask, postgresql and leaflet. I wanted to store coordinates (latitude and longitude) using PostGIS extender for postgresql. My flask application uses Flask-SQLAlchemy, blueprint and especially Flask-Migrate for the database migration process.

Here is an excerpt of my database model:

from . import db
from geoalchemy2 import Geometry


class Station(db.Model):
    __tablename__ = 'stations'

    id = db.Column(db.Integer, primary_key=True, unique=True)
    name = db.Column(db.String(255))
    position = db.Column(Geometry('Point', srid=4326))

Here an excerpt of my app/init.py

import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from config import config

db = SQLAlchemy()
migrate = Migrate()

def create_app(config_name=None, main=True):

if config_name is None:
    config_name = os.environ.get('FLASK_CONFIG', 'development')

app = Flask(__name__)
app.config.from_object(config[config_name])

db.init_app(app)
migrate.init_app(app, db)

from .home import home as home_blueprint
app.register_blueprint(home_blueprint)

from .admin import admin as admin_blueprint
app.register_blueprint(admin_blueprint, url_prefix='/admin')

return app

Before trying to use the specific extender, I didn't have any issue to adapt my model. Since then, the migration is doing alright but the upgrade doesn't work (python manage.py db upgrade).

Here the log I obtain from the webserver:

sa.Column('position', geoalchemy2.types.Geometry(geometry_type='POINT', srid=4326), nullable=True),
`enter code here`NameError: name 'geoalchemy2' is not defined

I'm a bit lost and I didn't find much help on this specific subject. Any idea on what might cause this issue?


Solution

  • Alembic does not try to determine and render all imports for custom types in the migration scripts. Edit the generated script to include from geoalchemy2.types import Geometry and change the column def to just use Geometry.

    You should always review the auto-generated scripts before running them. There's even comments in the script saying so.