Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 818
David Simic Avatar asked Dec 15 '15 15:12

David Simic


People also ask

How do I migrate a Flask model?

The normal migration process goes as follows: You will make some changes to your models in your Python source code. You will then run flask db migrate to generate a new database migration for these changes. You will finally apply the changes to the database by running flask db upgrade .

How do I create a migration repository in Flask?

To first set up your migrations directory, we can run flask db init . This creates a new migration repository; in so doing, this command creates a couple of folders and files in our project root where our migrations will live. We only need to do this once.

Which of the following commands creates a migration repository?

We need to use init command This creates a migration repository. This will add a migrations folder to your application. The contents of this folder need to be added to version control along with your other source files and see the Migrations folder in your project.

What is Flask_migrate?

Flask-Migrate is an extension that handles SQLAlchemy database migrations for Flask applications using Alembic. The database operations are provided as command-line arguments under the flask db command.


1 Answers

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.',
        ...
    )
...
like image 88
davidism Avatar answered Sep 30 '22 19:09

davidism