2

I'm starting a fastapi project, and using sqlalchemy + alembic to manage the sqlite db. Everything worked fine till alembic.

Here's the project folder structure:

app/
  - api/
  - core/
    - __init__.py
    - settings.py
  - db/
    - __init__.py
    - database.py

(I put a __init__.py in all folders)

At first, I tried to create migration folder inside db/, but with no success (same error as below). So I did alembic init migrations in root folder app/.

Now the folder looks like:

app/
  - api/
  - core/
    - __init__.py
    - settings.py
  - db/
    - __init__.py
    - database.py
  - migrations/
    - versions/
    - env.py
  - alembic.ini

And I modified the env.py:

from ..db.database import Base
from ..core.settings import settings

target_metadata = Base.metadata

def get_url():
    return settings.db_url

Then in app/, I tried

  • alembic revision --autogenerate -m "init"
  • python -m alembic.config revision --autogenerate -m "init"

But all complained:

...
  from ..db.database import Base
ImportError: attempted relative import with no known parent package

And since we have prepend_sys_path = . in alembic.ini, so imports like from db.database import Base would work. However I used relative imports in db/database.py and core/settings.py and all other files too and don't want to modify the codes.

My questions are:

  • Maybe I could put the migration folder outside the app/ and change relative import to app.db.database?
  • this might work for a single top level app, but what if I have several sub applications (app/subapps/sub1, app/subapps/sub2), and want to manage separated sqlite file for each sub application?
  • or maybe alembic is just not the right choice for my use case?
CSSer
  • 2,131
  • 2
  • 18
  • 37
  • Have you tried ```from db.database import Base from core.settings import settings``` ? You're in the root folder and thus going one step above is not possible, thus the error – lsabi Jan 28 '22 at 20:55
  • 1
    `alembic init` will handle that for you, just make sure to configure `env.py` according to the documentation and you project structure. – Mark Jan 30 '22 at 17:02

0 Answers0