django-tenants


Namedjango-tenants JSON
Version 3.6.0 PyPI version JSON
download
home_pagehttps://github.com/django-tenants/django-tenants
SummaryTenant support for Django using PostgreSQL schemas.
upload_time2023-12-04 22:26:57
maintainer
docs_urlNone
authorThomas Turner
requires_python
licenseMIT
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            django-tenants
==============
.. image:: https://badge.fury.io/py/django-tenants.svg
    :target: http://badge.fury.io/py/django-tenants

.. image:: https://github.com/tomturner/django-tenants/workflows/code/badge.svg
    :alt: Build status
    :target: https://github.com/tomturner/django-tenants/actions

.. image:: https://readthedocs.org/projects/pip/badge/?version=latest
    :target: https://django-tenants.readthedocs.io/en/latest/
    
.. image:: https://img.shields.io/pypi/dm/django-tenants.svg?maxAge=180
   :target: https://pypi.org/project/django-tenants/
   
.. image:: https://codecov.io/gh/django-tenants/django-tenants/branch/master/graph/badge.svg?token=wCNgSgTTR8
   :target: https://codecov.io/gh/django-tenants/django-tenants


This application enables `django`_ powered websites to have multiple
tenants via `PostgreSQL schemas`_. A vital feature for every
Software-as-a-Service (SaaS) website.

    Read the full documentation here: `django-tenants.readthedocs.org`_

Django provides currently no simple way to support multiple tenants
using the same project instance, even when only the data is different.
Because we don’t want you running many copies of your project, you’ll be
able to have:

-  Multiple customers running on the same instance
-  Shared and Tenant-Specific data
-  Tenant View-Routing



What are schemas
----------------

A schema can be seen as a directory in an operating system, each
directory (schema) with its own set of files (tables and objects). This
allows the same table name and objects to be used in different schemas
without conflict. For an accurate description on schemas, see
`PostgreSQL’s official documentation on schemas`_.

Why schemas
-----------

There are typically three solutions for solving the multitenancy
problem.

1. Isolated Approach: Separate Databases. Each tenant has its own
   database.

2. Semi Isolated Approach: Shared Database, Separate Schemas. One
   database for all tenants, but one schema per tenant.

3. Shared Approach: Shared Database, Shared Schema. All tenants share
   the same database and schema. There is a main tenant-table, where all
   other tables have a foreign key pointing to.

This application implements the second approach, which in our opinion,
represents the ideal compromise between simplicity and performance.

-  Simplicity: barely make any changes to your current code to support
   multitenancy. Plus, you only manage one database.
-  Performance: make use of shared connections, buffers and memory.

Each solution has its up and down sides. For a more in-depth
discussion, see Microsoft’s excellent article on `Multi-Tenant Data
Architecture`_.

How it works
------------

Tenants are identified via their host name (i.e tenant.domain.com). This
information is stored on a table on the ``public`` schema. Whenever a
request is made, the host name is used to match a tenant in the
database. If there’s a match, the search path is updated to use this
tenant’s schema. So from now on all queries will take place at the
tenant’s schema. For example, suppose you have a tenant ``customer`` at
http://customer.example.com. Any request incoming at
``customer.example.com`` will automatically use ``customer``\ ’s schema
and make the tenant available at the request. If no tenant is found, a
404 error is raised. This also means you should have a tenant for your
main domain, typically using the ``public`` schema. For more information
please read the `setup`_ section.

What can this app do?
---------------------

As many tenants as you want
~~~~~~~~~~~~~~~~~~~~~~~~~~~

Each tenant has its data on a specific schema. Use a single project
instance to serve as many as you want.

Tenant-specific and shared apps
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Tenant-specific apps do not share their data between tenants, but you
can also have shared apps where the information is always available and
shared between all.

Tenant View-Routing
~~~~~~~~~~~~~~~~~~~

You can have different views for ``http://customer.example.com/`` and
``http://example.com/``, even though Django only uses the string after
the host name to identify which view to serve.

Magic
~~~~~

Everyone loves magic! You’ll be able to have all this barely having to
change your code!

Setup & Documentation
---------------------

**This is just a short setup guide**. It is **strongly** recommended
that you read the complete version at
`django-tenants.readthedocs.org`_.

Your ``DATABASE_ENGINE`` setting needs to be changed to

.. code-block:: python

    DATABASES = {
        'default': {
            'ENGINE': 'django_tenants.postgresql_backend',
            # ..
        }
    }    

Add the middleware ``django_tenants.middleware.main.TenantMainMiddleware`` to the
top of ``MIDDLEWARE``, so that each request can be set to use
the correct schema.

.. code-block:: python

    MIDDLEWARE = (
        'django_tenants.middleware.main.TenantMainMiddleware',
        #...
    )
    
Add ``django_tenants.routers.TenantSyncRouter`` to your `DATABASE_ROUTERS`
setting, so that the correct apps can be synced depending on what's 
being synced (shared or tenant).

.. code-block:: python

    DATABASE_ROUTERS = (
        'django_tenants.routers.TenantSyncRouter',
    )

Add ``django_tenants`` to your ``INSTALLED_APPS``.

Create your tenant model
~~~~~~~~~~~~~~~~~~~~~~~~

.. code-block:: python

    from django.db import models
    from django_tenants.models import TenantMixin, DomainMixin

    class Client(TenantMixin):
        name = models.CharField(max_length=100)
        paid_until = models.DateField()
        on_trial = models.BooleanField()
        created_on = models.DateField(auto_now_add=True)

    class Domain(DomainMixin):
        pass

Define on ``settings.py`` which model is your tenant model. Assuming you
created ``Client`` inside an app named ``customers``, your
``TENANT_MODEL`` should look like this:

.. code-block:: python

    TENANT_MODEL = "customers.Client" # app.Model
    TENANT_DOMAIN_MODEL = "customers.Domain" # app.Model

Now run ``migrate_schemas``. This will sync your apps to the ``public``
schema.

.. code-block:: bash

    python manage.py migrate_schemas --shared

Create your tenants just like a normal django model. Calling ``save``
will automatically create and sync the schema.

.. code-block:: python

    from customers.models import Client, Domain

    # create your public tenant
    tenant = Client(schema_name='tenant1',
                    name='My First Tenant',
                    paid_until='2014-12-05',
                    on_trial=True)
    tenant.save()

    # Add one or more domains for the tenant
    domain = Domain()
    domain.domain = 'tenant.my-domain.com'
    domain.tenant = tenant
    domain.is_primary = True
    domain.save()

Any request made to ``tenant.my-domain.com`` will now automatically set
your PostgreSQL’s ``search_path`` to ``tenant1`` and ``public``, making
shared apps available too. This means that any call to the methods
``filter``, ``get``, ``save``, ``delete`` or any other function
involving a database connection will now be done at the tenant’s schema,
so you shouldn’t need to change anything at your views.

You’re all set, but we have left key details outside of this short
tutorial, such as creating the public tenant and configuring shared and
tenant specific apps. Complete instructions can be found at
`django-tenants.readthedocs.org`_.



Running the example project
---------------------------

django-tenants comes with an example project please see

`examples`_.


Credits
-------

I would like to thank two of the original authors of this project.

1. Bernardo Pires under the name `django-tenant-schemas`_.

2. Vlada Macek under the name of `django-schemata`_.

Requirements
------------

 - Django 2 if you want to use Django 1.11 or lower please use version 1 of django-tenants
 - PostgreSQL

Testing
-------

If you want to run tests, you can either run ``run_tests.sh`` (which requires access to
a PostgreSQL instance, location of which you can customize using the ``DATABASE_HOST``
env variable) or use `docker-compose`_ like this:

.. code-block:: bash

    ## Start Docker service
    # start docker   # with Upstart
    # systemctl start docker  # with systemd

    ## Install docker-compose (you might want to do this in Python virtualenv)
    # pip install docker-compose

    ## In main directory of this repo do:
    docker-compose run --rm django-tenants-test  # runs django-tenants tests.
    # dockerized PostgreSQL service is started implicitly

(note that upon first run the ``Dockerfile`` will be built).

Video Tutorial
--------------

An online video tutorial is available on `youtube`_.

Donation
--------

If this project helped you reduce development time, you can give me cake :)

.. image:: https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif
  :target: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=QU8BGC7DWB9G6&source=ur


.. _youtube: https://youtu.be/TWF7okf5Xoo
.. _django: https://www.djangoproject.com/
.. _PostgreSQL schemas: http://www.postgresql.org/docs/9.1/static/ddl-schemas.html
.. _PostgreSQL’s official documentation on schemas: http://www.postgresql.org/docs/9.1/static/ddl-schemas.html
.. _Multi-Tenant Data Architecture: https://web.archive.org/web/20160311212239/https://msdn.microsoft.com/en-us/library/aa479086.aspx
.. _setup: https://django-tenants.readthedocs.org/en/latest/install.html
.. _examples: https://django-tenants.readthedocs.org/en/latest/examples.html
.. _django-tenants.readthedocs.org: https://django-tenants.readthedocs.org/en/latest/
.. _django-tenant-schemas: http://github.com/bernardopires/django-tenant-schemas
.. _django-schemata: https://github.com/tuttle/django-schemata
.. _docker-compose: https://docs.docker.com/engine/reference/run/

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/django-tenants/django-tenants",
    "name": "django-tenants",
    "maintainer": "",
    "docs_url": null,
    "requires_python": "",
    "maintainer_email": "",
    "keywords": "",
    "author": "Thomas Turner",
    "author_email": "tom@twt.me.uk",
    "download_url": "https://files.pythonhosted.org/packages/fa/0c/24b6e993784ce8d9c840a76d1aa6e0fedf62f5dc8c1997b06dc9f5bb8ac1/django-tenants-3.6.0.tar.gz",
    "platform": null,
    "description": "django-tenants\n==============\n.. image:: https://badge.fury.io/py/django-tenants.svg\n    :target: http://badge.fury.io/py/django-tenants\n\n.. image:: https://github.com/tomturner/django-tenants/workflows/code/badge.svg\n    :alt: Build status\n    :target: https://github.com/tomturner/django-tenants/actions\n\n.. image:: https://readthedocs.org/projects/pip/badge/?version=latest\n    :target: https://django-tenants.readthedocs.io/en/latest/\n    \n.. image:: https://img.shields.io/pypi/dm/django-tenants.svg?maxAge=180\n   :target: https://pypi.org/project/django-tenants/\n   \n.. image:: https://codecov.io/gh/django-tenants/django-tenants/branch/master/graph/badge.svg?token=wCNgSgTTR8\n   :target: https://codecov.io/gh/django-tenants/django-tenants\n\n\nThis application enables `django`_ powered websites to have multiple\ntenants via `PostgreSQL schemas`_. A vital feature for every\nSoftware-as-a-Service (SaaS) website.\n\n    Read the full documentation here: `django-tenants.readthedocs.org`_\n\nDjango provides currently no simple way to support multiple tenants\nusing the same project instance, even when only the data is different.\nBecause we don\u2019t want you running many copies of your project, you\u2019ll be\nable to have:\n\n-  Multiple customers running on the same instance\n-  Shared and Tenant-Specific data\n-  Tenant View-Routing\n\n\n\nWhat are schemas\n----------------\n\nA schema can be seen as a directory in an operating system, each\ndirectory (schema) with its own set of files (tables and objects). This\nallows the same table name and objects to be used in different schemas\nwithout conflict. For an accurate description on schemas, see\n`PostgreSQL\u2019s official documentation on schemas`_.\n\nWhy schemas\n-----------\n\nThere are typically three solutions for solving the multitenancy\nproblem.\n\n1. Isolated Approach: Separate Databases. Each tenant has its own\n   database.\n\n2. Semi Isolated Approach: Shared Database, Separate Schemas. One\n   database for all tenants, but one schema per tenant.\n\n3. Shared Approach: Shared Database, Shared Schema. All tenants share\n   the same database and schema. There is a main tenant-table, where all\n   other tables have a foreign key pointing to.\n\nThis application implements the second approach, which in our opinion,\nrepresents the ideal compromise between simplicity and performance.\n\n-  Simplicity: barely make any changes to your current code to support\n   multitenancy. Plus, you only manage one database.\n-  Performance: make use of shared connections, buffers and memory.\n\nEach solution has its up and down sides. For a more in-depth\ndiscussion, see Microsoft\u2019s excellent article on `Multi-Tenant Data\nArchitecture`_.\n\nHow it works\n------------\n\nTenants are identified via their host name (i.e tenant.domain.com). This\ninformation is stored on a table on the ``public`` schema. Whenever a\nrequest is made, the host name is used to match a tenant in the\ndatabase. If there\u2019s a match, the search path is updated to use this\ntenant\u2019s schema. So from now on all queries will take place at the\ntenant\u2019s schema. For example, suppose you have a tenant ``customer`` at\nhttp://customer.example.com. Any request incoming at\n``customer.example.com`` will automatically use ``customer``\\ \u2019s schema\nand make the tenant available at the request. If no tenant is found, a\n404 error is raised. This also means you should have a tenant for your\nmain domain, typically using the ``public`` schema. For more information\nplease read the `setup`_ section.\n\nWhat can this app do?\n---------------------\n\nAs many tenants as you want\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nEach tenant has its data on a specific schema. Use a single project\ninstance to serve as many as you want.\n\nTenant-specific and shared apps\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nTenant-specific apps do not share their data between tenants, but you\ncan also have shared apps where the information is always available and\nshared between all.\n\nTenant View-Routing\n~~~~~~~~~~~~~~~~~~~\n\nYou can have different views for ``http://customer.example.com/`` and\n``http://example.com/``, even though Django only uses the string after\nthe host name to identify which view to serve.\n\nMagic\n~~~~~\n\nEveryone loves magic! You\u2019ll be able to have all this barely having to\nchange your code!\n\nSetup & Documentation\n---------------------\n\n**This is just a short setup guide**. It is **strongly** recommended\nthat you read the complete version at\n`django-tenants.readthedocs.org`_.\n\nYour ``DATABASE_ENGINE`` setting needs to be changed to\n\n.. code-block:: python\n\n    DATABASES = {\n        'default': {\n            'ENGINE': 'django_tenants.postgresql_backend',\n            # ..\n        }\n    }    \n\nAdd the middleware ``django_tenants.middleware.main.TenantMainMiddleware`` to the\ntop of ``MIDDLEWARE``, so that each request can be set to use\nthe correct schema.\n\n.. code-block:: python\n\n    MIDDLEWARE = (\n        'django_tenants.middleware.main.TenantMainMiddleware',\n        #...\n    )\n    \nAdd ``django_tenants.routers.TenantSyncRouter`` to your `DATABASE_ROUTERS`\nsetting, so that the correct apps can be synced depending on what's \nbeing synced (shared or tenant).\n\n.. code-block:: python\n\n    DATABASE_ROUTERS = (\n        'django_tenants.routers.TenantSyncRouter',\n    )\n\nAdd ``django_tenants`` to your ``INSTALLED_APPS``.\n\nCreate your tenant model\n~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. code-block:: python\n\n    from django.db import models\n    from django_tenants.models import TenantMixin, DomainMixin\n\n    class Client(TenantMixin):\n        name = models.CharField(max_length=100)\n        paid_until = models.DateField()\n        on_trial = models.BooleanField()\n        created_on = models.DateField(auto_now_add=True)\n\n    class Domain(DomainMixin):\n        pass\n\nDefine on ``settings.py`` which model is your tenant model. Assuming you\ncreated ``Client`` inside an app named ``customers``, your\n``TENANT_MODEL`` should look like this:\n\n.. code-block:: python\n\n    TENANT_MODEL = \"customers.Client\" # app.Model\n    TENANT_DOMAIN_MODEL = \"customers.Domain\" # app.Model\n\nNow run ``migrate_schemas``. This will sync your apps to the ``public``\nschema.\n\n.. code-block:: bash\n\n    python manage.py migrate_schemas --shared\n\nCreate your tenants just like a normal django model. Calling ``save``\nwill automatically create and sync the schema.\n\n.. code-block:: python\n\n    from customers.models import Client, Domain\n\n    # create your public tenant\n    tenant = Client(schema_name='tenant1',\n                    name='My First Tenant',\n                    paid_until='2014-12-05',\n                    on_trial=True)\n    tenant.save()\n\n    # Add one or more domains for the tenant\n    domain = Domain()\n    domain.domain = 'tenant.my-domain.com'\n    domain.tenant = tenant\n    domain.is_primary = True\n    domain.save()\n\nAny request made to ``tenant.my-domain.com`` will now automatically set\nyour PostgreSQL\u2019s ``search_path`` to ``tenant1`` and ``public``, making\nshared apps available too. This means that any call to the methods\n``filter``, ``get``, ``save``, ``delete`` or any other function\ninvolving a database connection will now be done at the tenant\u2019s schema,\nso you shouldn\u2019t need to change anything at your views.\n\nYou\u2019re all set, but we have left key details outside of this short\ntutorial, such as creating the public tenant and configuring shared and\ntenant specific apps. Complete instructions can be found at\n`django-tenants.readthedocs.org`_.\n\n\n\nRunning the example project\n---------------------------\n\ndjango-tenants comes with an example project please see\n\n`examples`_.\n\n\nCredits\n-------\n\nI would like to thank two of the original authors of this project.\n\n1. Bernardo Pires under the name `django-tenant-schemas`_.\n\n2. Vlada Macek under the name of `django-schemata`_.\n\nRequirements\n------------\n\n - Django 2 if you want to use Django 1.11 or lower please use version 1 of django-tenants\n - PostgreSQL\n\nTesting\n-------\n\nIf you want to run tests, you can either run ``run_tests.sh`` (which requires access to\na PostgreSQL instance, location of which you can customize using the ``DATABASE_HOST``\nenv variable) or use `docker-compose`_ like this:\n\n.. code-block:: bash\n\n    ## Start Docker service\n    # start docker   # with Upstart\n    # systemctl start docker  # with systemd\n\n    ## Install docker-compose (you might want to do this in Python virtualenv)\n    # pip install docker-compose\n\n    ## In main directory of this repo do:\n    docker-compose run --rm django-tenants-test  # runs django-tenants tests.\n    # dockerized PostgreSQL service is started implicitly\n\n(note that upon first run the ``Dockerfile`` will be built).\n\nVideo Tutorial\n--------------\n\nAn online video tutorial is available on `youtube`_.\n\nDonation\n--------\n\nIf this project helped you reduce development time, you can give me cake :)\n\n.. image:: https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif\n  :target: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=QU8BGC7DWB9G6&source=ur\n\n\n.. _youtube: https://youtu.be/TWF7okf5Xoo\n.. _django: https://www.djangoproject.com/\n.. _PostgreSQL schemas: http://www.postgresql.org/docs/9.1/static/ddl-schemas.html\n.. _PostgreSQL\u2019s official documentation on schemas: http://www.postgresql.org/docs/9.1/static/ddl-schemas.html\n.. _Multi-Tenant Data Architecture: https://web.archive.org/web/20160311212239/https://msdn.microsoft.com/en-us/library/aa479086.aspx\n.. _setup: https://django-tenants.readthedocs.org/en/latest/install.html\n.. _examples: https://django-tenants.readthedocs.org/en/latest/examples.html\n.. _django-tenants.readthedocs.org: https://django-tenants.readthedocs.org/en/latest/\n.. _django-tenant-schemas: http://github.com/bernardopires/django-tenant-schemas\n.. _django-schemata: https://github.com/tuttle/django-schemata\n.. _docker-compose: https://docs.docker.com/engine/reference/run/\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Tenant support for Django using PostgreSQL schemas.",
    "version": "3.6.0",
    "project_urls": {
        "Homepage": "https://github.com/django-tenants/django-tenants"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "fa0c24b6e993784ce8d9c840a76d1aa6e0fedf62f5dc8c1997b06dc9f5bb8ac1",
                "md5": "d003a70a16351fb03a321571543eff93",
                "sha256": "233c6bcc5643e3c5acf6c7d429f5b8106bba088f5dde3a8b3154e9417a456bcc"
            },
            "downloads": -1,
            "filename": "django-tenants-3.6.0.tar.gz",
            "has_sig": false,
            "md5_digest": "d003a70a16351fb03a321571543eff93",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 117749,
            "upload_time": "2023-12-04T22:26:57",
            "upload_time_iso_8601": "2023-12-04T22:26:57.144012Z",
            "url": "https://files.pythonhosted.org/packages/fa/0c/24b6e993784ce8d9c840a76d1aa6e0fedf62f5dc8c1997b06dc9f5bb8ac1/django-tenants-3.6.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-12-04 22:26:57",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "django-tenants",
    "github_project": "django-tenants",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "requirements": [],
    "lcname": "django-tenants"
}
        
Elapsed time: 0.14375s