Search code examples
pythonflaskalembicflask-migrate

How to autoimport module in flask-migrate migration


My flask project uses sqlalchemy_utils in some of its model definitions, which causes migration errors like:

NameError: global name 'sqlalchemy_utils' is not defined

due to this package not being imported in the migration files.

I'd like to have flask-migrate / alembic autogenerate the lines importing this package into the migration files, how do I achieve this?

I've looked at alembic.ini and migrations/env.py - but it's not obvious to me what is the right way / if it's possible at all.


Solution

  • The most straightforward way is to modify the template to include that import.

    script.py.mako:

    ...
    from alembic import op
    import sqlalchemy as sa
    import sqlalchemy_utils
    ${imports if imports else ''}
    ...
    

    If you have multiple modules that provide custom types, you can use the strategy described in the docs. Create a module in your project that imports the different modules, then set that as the prefix Alembic should use for user types.

    /myapp/migration_types.py:

    from sqlalchemy_utils import *
    from myapp.custom_model_type import MyType
    

    script.py.mako:

    ...
    from myapp import migration_types
    ...
    

    env.py:

    ...
    def run_migrations_online():
        ...
        context.configure(
            ...
            user_module_prefix='migration_types.',
            ...
        )
    ...