alembic で modelクラスを全てまるっとインポートする

はじめに alembic 自動生成する際に、指定ディレクトリ配下のクラスを全てまるっとインポートする方法 問題 疑問 自動生成したい対象のModelクラスをインポートしないと生成してくれない まとめ 結果 解決方法 以下を env.py 先頭に追記して、 app/models 配下の全てのクラスをインポートする # Import all models in app.models model_path = os.path.dirname(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../app/models/')) for py in [f[:-3] for f in os.listdir(model_path) if f.endswith('.py') and (f != '__init__.py' and f != 'base_model.py')]: mod = __import__('.'.join(['app.modesl', py])) classes = [getattr(mod, x) for x in dir(mod) if isinstance(getattr(mod, x), type)] for cls in classes: setattr(sys.modules[__name__], cls.__name__, cls) Refs python - Import all classes in directory?...

2024-07-04 ·  2024-08-02 · 1 分 · 76 文字

Alembic revision --autogenerate で変更がなくても空のrevisionファイルができるのを避ける

はじめに Alembic revision –autogenerate で変更がなくても空のrevisionファイルができるのを避ける python 3.11, alembic 1.7.7, sqlalchemy 2.0.30, sqlmodel 0.0.18 問題 疑問 変更がなくても空のrevisionファイルが生成されてしまう まとめ 結果 解決方法 以下のような process_revision_directives を設定することで、差分がない場合は空のrevisionファイルを生成しない def run_migrations_online(): : def process_revision_directives(context, revision, directives): if config.cmd_opts.autogenerate: script = directives[0] if script.upgrade_ops.is_empty(): directives[:] = [] print('No changes in schema detected.') : with connectable.connect() as connection: context.configure( connection=connection, target_metadata=target_metadata, include_schemas=True, dialect_opts={"paramstyle": "named"}, include_name=include_name, process_revision_directives=process_revision_directives, ) Refs python - How to prevent alembic revision –autogenerate from making revision file if it has not detected any changes?...

2024-07-04 ·  2024-08-02 · 1 分 · 81 文字