Alembic migration for GeoAlchemy2 raises NameError: name 'geoalchemy2' is not defined
<p>I've decided to write a small webapp using Flask, postgresql and leaflet. I wanted to store coordinates (latitude and longitude) using <a href="http://postgis.net/" rel="nofollow">PostGIS</a> extender for postgresql. My flask application uses Flask-SQLAlchemy, blueprint and especially Flask-Migrate for the database migration process.</p>

<p>Here is an excerpt of my database model:</p>

<pre><code>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))
</code></pre>

<p>Here an excerpt of my app/<strong>init</strong>.py</p>

<pre><code>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
</code></pre>

<p>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).</p>

<p>Here the log I obtain from the webserver:</p>

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

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

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

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

python postgresql flask alembic geoalchemy2