28

FlaskプロジェクトをAlembic
アプリケーション構造と統合しようとしています。

project/
       configuration/
                    __init__.py
                    dev.py
                    test.py
       core/
           # all source code
       db/
         migrations/
                    __init__.py
                    alembic.ini
                    env.py
                    versions/

dbディレクトリから次のコマンドを実行しようとすると、次のように表示されます。

 File "migration/env.py", line 55, in run_migrations_online
    from configuration import app, db
ImportError: No module named configuration

移行の自動生成のための簡単なアランビック作業例のリクエストで説明した解決策を試しましたが、うまくいきません

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

どうすればこれを修正できますか?

4

4 に答える 4

44

I did export PYTHONPATH=<path_to_project> and ran the command again and it ran successfully

于 2013-04-02T16:22:59.513 に答える
17

You say you run something like alembic migrate --autogenerate -m 'migration description' from the directory project/db and get ImportError, right?

If so, the problem is obvious.

See: you try to import configuration module and it results in errors. Then you put sys.path.append(os.getcwd()) - in other words, you add current directory to the system path. But what is the current directory? It's project/db, and it doesn't have configuration module under it, so you continue getting ImportError.

Solution is to add to system path parent directory - project, which contains configuration module. Like so:

parent_dir = os.path.abspath(os.path.join(os.getcwd(), ".."))
sys.path.append(parent_dir)
于 2013-03-31T21:22:05.753 に答える
2

同じ問題が発生しました。フラグが設定されていない限り、リビジョンによってenv.pyが呼び出されないことになります。--autogenerateこれをテストするには、env.pyファイルの先頭にprintステートメントを配置します。

で呼び出して--autogenerateから生成されたコードを削除することで、この問題を回避しています。

于 2013-03-30T21:18:13.197 に答える
0

For those who don't want to set PYTHONPATH manually before running alembic. You may run alembic as a module, for instance:

python -m alembic.config upgrade head
于 2021-08-29T05:50:33.343 に答える