【问题标题】:Alembic migration for GeoAlchemy2 raises NameError: name 'geoalchemy2' is not definedGeoAlchemy2 的 Alembic 迁移引发 NameError:未定义名称“geoalchemy2”
【发布时间】:2017-01-06 00:25:26
【问题描述】:

我决定使用 Flask、postgresql 和 Leaflet 编写一个小型 Web 应用程序。我想使用 PostGIS 扩展器为 postgresql 存储坐标(纬度和经度)。我的烧瓶应用程序使用 Flask-SQLAlchemy、蓝图,尤其是 Flask-Migrate 进行数据库迁移过程。

这是我的数据库模型的摘录:

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

这里是我的应用程序的摘录/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

在尝试使用特定扩展器之前,我没有任何问题来调整我的模型。从那时起,迁移工作正常,但升级不起作用(python manage.py db upgrade)。

这里是我从网络服务器获取的日志:

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

我有点迷茫,在这个特定主题上我没有找到太多帮助。关于可能导致此问题的任何想法?

【问题讨论】:

    标签: python postgresql flask alembic geoalchemy2


    【解决方案1】:

    Alembic 不会尝试确定和呈现迁移脚本中自定义类型的所有导入。编辑生成的脚本以包含 from geoalchemy2.types import Geometry 并将列 def 更改为仅使用 Geometry

    在运行自动生成的脚本之前,您应该始终查看它们。剧本里甚至有cmets这么说。

    【讨论】:

      【解决方案2】:

      另一种不需要手动编辑修订的方法是将import geoalchemy2 添加到alembic/script.py.mako 中,然后alembic 每次都添加该模块。

      """${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"}
      

      【讨论】:

        猜你喜欢
        • 2020-02-12
        • 1970-01-01
        • 1970-01-01
        • 2018-01-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-14
        相关资源
        最近更新 更多