A demonstration application using FastAPI and ormar.
ENVIRONMENT=develop
When using ormar, we need to make migration files by ourselves. For this we use alembic.
alembic init migrations
migrations
is a name of the folder. This can be anything.
When making a migration for your models, you need to import the models into env.py
created by alembic and set the metadata to target_metadata
.
# in migrations/env.py
from .models import Book
from .database import metadata
target_metadata = metadata
Usually you would need to set the sqlalchemy.url
in your alembic file. But in order to make this connection more dynamic, we set this value in env.py
as follows.
# in migrations/env.py
from .database import get_db_url
target_metadata = metadata
config.set_main_option("sqlalchemy.url", get_db_url())
alembic revision --autogenerate -m "<write migration comments>"
After Step4, checked the auto generated migration file.
If you see ormar
in the file, please import the ormar
package inside the file.
If you skip this step, Step6 will fail.
alembic upgrade head
uvicorn app.main:app --reload
If you want to use a different database for running unit tests, change the value of environment variable ENVIRONMENT to test
from .settings import settings
TEST_DB_URL = f"sqlite:///{str(settings.base_dir)}/db/test_db.sqlite"
DB_URL = f"sqlite:///{str(settings.base_dir)}/db/dev_db.sqlite"
# DB_URL = f"postgresql://root:root1234@db:5432/dev_db" # your DB url
def get_db_url():
if settings.environment == "test":
return TEST_DB_URL
return DB_URL
Not deployed.