6

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?

davidism
  • 121,510
  • 29
  • 395
  • 339
mattberjon
  • 105
  • 2
  • 8

2 Answers2

8

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.

davidism
  • 121,510
  • 29
  • 395
  • 339
1

Another way to do this which doesn't require manually editing the revision is adding import geoalchemy2 into alembic/script.py.mako and then alembic adds the module every time.

"""${message}
  
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}

"""
from alembic import op
import sqlalchemy as sa
import geoalchemy2 # <--- right here
${imports if imports else ""}

# revision identifiers, used by Alembic.
revision = ${repr(up_revision)}
down_revision = ${repr(down_revision)}
branch_labels = ${repr(branch_labels)}
depends_on = ${repr(depends_on)}


def upgrade():
    ${upgrades if upgrades else "pass"}


def downgrade():
    ${downgrades if downgrades else "pass"}