Example of multi-tenancy using Django 1.11 and MySql.
First of all, have pip and virtualenv installed.
-
Create a virtualenv for the project by prescribing Python 3:
virtualenv --python = python3 [environment name]
-
Enter the virtualenv folder and activate it:
source bin/activate
-
To install the
mysqlclient
driver make sure you have installed the dependencies below:
sudo apt-get install python-dev python3-dev
sudo apt-get install libmysqlclient-dev
-
Install the required packages:
pip install -r requirements.txt
(NOTE) some bugs were found in thedjango-db-multitenant==0.3.2
library. So a fork was created with the problem already fixed (https://github.com/diegofsousa/django-db-multitenant). The above command already installs the version with bugs fixed. -
Create the databases in mysql command line. In the following example we will use two tenants (
tenant1
andtenant2
), however you can change it with whatever you want. NOTE: Each database will be a tenant. Here is an example of how it should be created:
CREATE DATABASE tenant1 CHARACTER SET utf8;
CREATE DATABASE tenant2 CHARACTER SET utf8;
-
Make the database settings in
settings.py
as follows:
DATABASES = {
'default': {
'ENGINE': 'db_multitenant.db.backends.mysql',
'NAME': 'tenant',
'USER': 'YOUR DATABASE USERNAME',
'PASSWORD': 'YOUR DATABASE PASSWORD',
'HOST': 'localhost',
'PORT': 'YOUR DATABASE PORT',
}
}
One of the tenants will be used in this configuation only for Django not to complain about syntax error.
- Add the hosts file (in Linux OS:
/etc/hosts/
) for your computer, pointing to127.0.0.1
as the tenants were created:
127.0.0.1 tenant1.example
127.0.0.1 tenant2.example
-
Migrate the databases:
TENANT_DATABASE_NAME=tenant1 ./manage.py migrate
TENANT_DATABASE_NAME=tenant2 ./manage.py migrate
-
Run your application with
./manage.py runserver
and access your tenants with:
http://tenant1.example:8000
for tenant1 andhttp://tenant2.example:8000
for tenant2.
- Diego Fernando and Renan Xavier.