The problem with importing when creating an Alembic migration

22 Views Asked by At

I have such a file structure:

├───auth_service
│   ├── alembic
│   │   |___versions
│   │   │___env.py
│   │  
│   |── src
|   |    |___config.py
|   |
|   |___alembic.ini
│  
├───market_service

alembic.ini file:

[alembic]
script_location = alembic
prepend_sys_path = .
version_path_separator = os
sqlalchemy.url = .
...

alembic/env.py file:

from auth_service.src.config import env_config
from auth_service.src.core.engines.postgres_engine import Base

config = context.config
config.set_main_option('sqlalchemy.url', env_config.postgres_url())

if config.config_file_name is not None:
    fileConfig(config.config_file_name)


target_metadata = Base.metadata


def run_migrations_offline() -> None:
    url = config.get_main_option("sqlalchemy.url")
    context.configure(
        url=url,
        target_metadata=target_metadata,
        literal_binds=True,
        dialect_opts={"paramstyle": "named"},
    )

    with context.begin_transaction():
        context.run_migrations()
...

When I try to run the alembic revision --autogenerate -m 'text' command from .../project/auth_service , I get an error:

File "C:\Users\user\PycharmProjects\Microservices-FastAPI\auth_service\alembic\env.py", line 8, in <module>
    from auth_service.src.config import env_config
ModuleNotFoundError: No module named 'auth_service'

I tried adding __init__.py files to all directories involved in the process and change the import path from:

from auth_service.src.config import env_config
from auth_service.src.core.engines.postgres_engine import Base

to:

from ..src.config import env_config
from ..src.core.engines.postgres_engine import Base

But it led me to a mistake:

File "C:\Users\user\PycharmProjects\Microservices-FastAPI\auth_service\alembic\env.py", line 8, in <module>
    from ..src.config import env_config
ImportError: attempted relative import with no known parent package

0

There are 0 best solutions below