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.
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 .
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.
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.
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.
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.',
...
)
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With