Django - Shared App & Isolated Databases
An app that demonstrates the implementation of: One Database Per User/Customer
. The logic is handled in a single application instance.
In other words, each user should have their own database. Most SaaS products run in this architecture of data handling.
Working Of The Logic:
- There is a centralized
routing-table
which pointsuser1
todatabase1
. - While user creation, the routing-table instance is created on the default database.
- The database is created dynamically on runtime for the user. The user instance is then created on the user specific database.
- While login, the routing table is searched with the
username
or the unique identifier. - Depending on the database where the user's data is stored. The auth credentials are checked and then authenticated.
- After authentication, the database to be used is set on the
local-thread
. - We have customised the
database-router
to get the data from thelocal-thread
and query accordingly. - We have also used
cookies
to persist the user's auth and related data.
Prerequisites
- Python3.9.6
- Virtualenv
Getting Started Locally
- Create a virtual environment in the project root using
virtualenv -p python3 venv
. - Activate the environment & install the packages inside
requirements.txt
file. - Use pre-commit to maintain code integrity. Run:
pre-commit install
. - Run the app using
python manage.py migrate && python manage.py runserver
.
References Used
- https://books.agiliq.com/projects/django-multi-tenant/en/latest/isolated-database.html
- https://oroinc.com/b2b-ecommerce/blog/single-tenant-vs-multi-tenant/
Your thoughts, suggestions, feedback, comments and PR's are welcome