A Scalable Web Application with Efficient Database Management
A website, that serves multiple users or groups, also known as tenants.Each tenant company1.example.com has its own database schema.
Fork this repository to get started with a multi-tenant system using FastAPI, PostgreSQL, Alembic, Docker, Ruff, Pdm, Typer, and more.
-
Clone the repository
-
Install PDM (Python Development Master) package manager:
pip install pdm --user
-
Create and activate the virtual environment
pdm venv create --with venv
pdm use
eval $(pdm venv activate )
-
May need to upgrade:
rustup default nightly && rustup updatepdm install --no-self
Create a .env file in the root directory and add the following environment variables:
ENVIRONMENT=development
DB_NAME=db_name
DB_USER=user
DB_PASS=root
DB_PORT=5432
DB_HOST=localhost
PGADMIN_DEFAULT_EMAIL=user@user.com
PGADMIN_DEFAULT_PASSWORD=password- Alternatively you can setup a GCP database following the instructions in [.guide/gcp_database]
-
Start postgres database in docker
docker-compose -f .local_database/postgres_compose.yml --env-file .env up
-
Login to PG Admin
- open localhost
- login with the credentials you provided in the
.envfilePGADMIN_DEFAULT_EMAILPGADMIN_DEFAULT_PASSWORD
-
Setup PGAdmin Access to database
Add a new server
Register->Serverwith the following details:General: # or any name you prefer Name: myserver Connection: # as configured in .local_database/postgres_compose.yml Port: 5432 (from docker container) Hostname/address: db Username: postgres Password: postgres
-
Run alembic migrations:
alembic upgrade head
-
Run management command
python manage.py --helpfor more information
python manage.py tenant create_tenant company1 company1 company1.localhost
-
Run the application
pdm run start # equivalent to: uvicorn multi_tenancy_system.main:app --reload --app-dir ./src -
Access the interactive API documentation:
- Open your browser and go to http://localhost:8000/docs for Swagger UI.
- Alternatively, access http://localhost:8000/redoc for ReDoc.
- PDM
- Modern Python package manager, Specify dependencies in a
pyproject.tomlfile. - add package in pyproject.toml file
pdm add package_name - add package to dev dependencies
pdm add package_name --dev
- Modern Python package manager, Specify dependencies in a
- Typer - Typer is a library for building CLI applications that users will love using and developers will love creating.
- Ruff - A simple and fast web framework for Python
- Alembic
- See .guide/alembic_commands.md for more information on how to use Alembic.
- Pydantic - Data validation and settings management using Python type hints.
- Uvicorn - ASGI server implementation, using uvloop and httptools.
This project is licensed under the MIT License - see the LICENSE file for details.