Alembic:alembic修订版称导入错误

day*_*mer 23 python flask flask-sqlalchemy alembic

我正在尝试将我的Flask项目与Alembic
我的应用程序结构集成

project/
       configuration/
                    __init__.py
                    dev.py
                    test.py
       core/
           # all source code
       db/
         migrations/
                    __init__.py
                    alembic.ini
                    env.py
                    versions/
Run Code Online (Sandbox Code Playgroud)

当我尝试从我的db目录运行以下内容时,我明白了

 File "migration/env.py", line 55, in run_migrations_online
    from configuration import app, db
ImportError: No module named configuration
Run Code Online (Sandbox Code Playgroud)

我尝试了请求一个简单的alembic工作示例中提到的自动生成迁移的解决方案,但它对我不起作用

env.py run_migrations_online()改变的方法是

def run_migrations_online():
    """Run migrations in 'online' mode.

    In this scenario we need to create an Engine
    and associate a connection with the context.

    """
    import os
    import sys

    sys.path.append(os.getcwd())
    from configuration import app, db

    alembic_config = config.get_section(config.config_ini_section)
    alembic_config['sqlalchemy.url'] = app.config['SQLALCHEMY_DATABASE_URI']
    target_metadata = db.metadata

    engine = engine_from_config(
        alembic_config,
        prefix='sqlalchemy.',
        poolclass=pool.NullPool)

    connection = engine.connect()
    context.configure(
        connection=connection,
        target_metadata=target_metadata
    )

    try:
        with context.begin_transaction():
            context.run_migrations()
    finally:
        connection.close()


if context.is_offline_mode():
    run_migrations_offline()
else:
    run_migrations_online()
Run Code Online (Sandbox Code Playgroud)

我怎样才能解决这个问题?

day*_*mer 37

我做了export PYTHONPATH=<path_to_project>并再次运行命令,它成功运行

  • PYTHONPATH=. 将包含当前目录,它也能达到目的。 (3认同)

Pal*_*aty 14

你说你alembic migrate --autogenerate -m 'migration description'从目录运行的东西project/db得到了ImportError,对吧?

如果是这样,问题是显而易见的.

请参阅:您尝试导入configuration模块并导致错误.然后你把sys.path.append(os.getcwd())- 换句话说,你将当前目录添加到系统路径.但目前的目录是什么?它是project/db,它下面没有configuration模块,所以你继续得到ImportError.

解决方案是添加到系统路径父目录 - project,其中包含configuration模块.像这样:

parent_dir = os.path.abspath(os.path.join(os.getcwd(), ".."))
sys.path.append(parent_dir)
Run Code Online (Sandbox Code Playgroud)