Django and SaaS. How to use separate database for

2019-03-22 09:34发布

I am creating a SaaS project with Django. I decided to use django-saas-kit for the user subscriptions and multi-accounts part.

Ideally I would like to be able to create a new site for each user and a separate database. Does the sites framework support this? How can it be implemented?

Thanks.

1条回答
beautiful°
2楼-- · 2019-03-22 09:41

You should create a "clients" folder, and a subdirectory per client. In each subdirectory, create a site_settings.py file as such:

import os.path

# import global settings
from settings import *

# this is barely just the name of the client dir, you might want to use that
SITE_NAME = __file__.split('/')[-2]
# this is the directory of the client website
CLIENT_ROOT = os.path.abspath(os.path.dirname(__file__))

DATABASES = {
    'default': {
        'ENGINE': 'django.contrib.gis.db.backends.postgis',
        'NAME': SITE_NAME,
        'USER': SITE_NAME,
        'PASSWORD': 'some random password',
    }  
}

# you might want this too so that each client have his own MEDIA_ROOT
MEDIA_ROOT = os.path.join(CLIENT_ROOT, 'upload')

Then don't forget to use the --settings switch for management commands. For example:

./manage.py syncdb --settings=clients.demo.site_settings

Don't forget that each client will require to have his own extra stuff. For example, if you use haystack with whoosh, you need to add this so that it doesn't get mixed up between clients:

HAYSTACK_WHOOSH_PATH = os.path.join(CLIENT_ROOT, 'whoosh')

Or with django-zstask:

ZTASKD_URL = 'ipc:///tmp/%s_ztask.sock' % SITE_NAME

Or with JohnnyCache:

JOHNNY_MIDDLEWARE_KEY_PREFIX=SITE_NAME
查看更多
登录 后发表回答