如何在容器迁移迁移中自动导入模块 [英] How to autoimport module in flask-migrate migration
问题描述
NameError:global name' sqlalchemy_utils'未定义
由于这个软件包没有被导入到迁移文件中。
我想用flask-migrate / alembic自动生成将这个包导入到迁移文件中的行,我该如何实现这个功能?
我已经看过alembic.ini和migrations / env.py - 但是对于我来说,什么是正确的方法/如果可能的话,我不是很清楚。
最直接的方法是修改模板以包含该导入。
script.py .mako
:
...
from alembic import op
import sqlalchemy as sa
import sqlalchemy_utils
{import if import else''}
...
如果你有多个模块提供自定义类型,你可以使用策略在文档中描述。在您的项目中创建一个导入不同模块的模块,然后将其设置为前缀Alembic应该用于用户类型。
$ b $ p / 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
:
<$ p $ (
$ b $ ...
def run_migrations_online():
...
context.configure(
...
user_module_prefix ='migration_types ',
...
)
...
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 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.',
...
)
...
这篇关于如何在容器迁移迁移中自动导入模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!