My Django1.10 Settings

14th February, 2019
"""
Django settings for shubhamdipt project.

Generated by 'django-admin startproject' using Django 1.10.5.

For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""

import os
import json
import cloudinary
import raven


PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
#ToDo: Create an environment variable DEP_NAME=shubhamdipt/master
# DEP_NAME determines the stage of the environment: (master, staging, development)
DEP_NAME = os.getenv('DEP_NAME', 'x/local').split("/")[1]
VERSION = 1

# for Redirection
#ToDo: Create an environment variable PROJECT_DOMAIN=www.shubhamdipt.com
# PROJECT_DOMAIN checks the incoming url and 301 redirects to the correct domain.
PROJECT_DOMAIN = os.environ.get('PROJECT_DOMAIN')  # only Production environment
#SUBDOMAIN_REDIRECT determines if the subdomains should be redirected to the correct domain.  
SUBDOMAIN_REDIRECT = True
#SSL_REDIRECT redirects the HTTP to HTTPS
SSL_REDIRECT = False


'''########################################################################
#######                     Django Basic                              #####
########################################################################'''

# Application definition

INSTALLED_APPS = (
    'suit', # for Admin styling
    'suit_rq', # for Admin styling for rq jobs
    'dal', # for autocompletion
    'dal_select2',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',
    'django.contrib.sitemaps',
    'django.contrib.admin',
    'django.contrib.humanize',
    'crispy_forms', # for form styling
    'cloudinary', # Cloudinary as CDN for images
)

MIDDLEWARE_CLASSES = (
    'shubhamdipt.middleware.SubdomainRedirect',
    'django.middleware.gzip.GZipMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
)

ROOT_URLCONF = 'shubhamdipt.urls'

WSGI_APPLICATION = 'shubhamdipt.wsgi.application'

LANGUAGES = (
    # ('de', 'Deutsch'),
    ('en', 'English'),
)

LOCALE_PATHS = (
    os.path.join(PROJECT_ROOT, 'locale'),
)

LANGUAGE_CODE = 'en'

TIME_ZONE = 'Europe/Berlin'

USE_I18N = True

USE_L10N = True

USE_TZ = True

SITE_ID = 1


'''########################################################################
#######                     DEPLOYMENT                              #####
########################################################################'''

config = {
   key: value for key, value in os.environ.items()
}
aws_database_url = config.get('RDS_DB_NAME', None)
heroku_database_url = config.get('DATABASE_URL', None)
docker = config.get('DOCKER', None)

if aws_database_url:
    # AWS production settings
    DEBUG = False
    SECRET_KEY = config.get('SECRET_KEY')
    ALLOWED_HOSTS = ['*']

    # For sentry settings
    INSTALLED_APPS += (
       'raven.contrib.django.raven_compat',
    )
    RAVEN_CONFIG = {
       'dsn': config.get('SENTRY_DSN', ''),
    }

    # Database settings
    DATABASES = {
        'default': {
           'ENGINE': 'django.db.backends.postgresql',
           'NAME': os.environ['RDS_DB_NAME'],
           'USER': os.environ['RDS_USERNAME'],
           'PASSWORD': os.environ['RDS_PASSWORD'],
           'HOST': os.environ['RDS_HOSTNAME'],
           'PORT': os.environ['RDS_PORT'],
        }
    }
elif heroku_database_url:
    # HEROKU production settings
    DEBUG = False
    SECRET_KEY = config.get('SECRET_KEY')
    ALLOWED_HOSTS = ['*']
    import dj_database_url
    DATABASES = {
       'default': dj_database_url.parse(heroku_database_url),
    }
    # For sentry settings
    INSTALLED_APPS += (
       'raven.contrib.django.raven_compat',
    )
    RAVEN_CONFIG = {
       'dsn': config.get('SENTRY_DSN', ''),
    }
elif docker:
    # Docker settings
    DEBUG = True
    cred_file = open(os.path.join(PROJECT_ROOT, 'local_config.json'))
    creds = json.load(cred_file)
    config = creds.get('CONFIG')
    SECRET_KEY = config.get("SECRET_KEY")
    ALLOWED_HOSTS = ['0.0.0.0']
    DATABASES = {
       'default': {
           'ENGINE': 'django.db.backends.postgresql',
           'NAME': 'postgres',
           'USER': 'postgres',
           'HOST': 'db',
           'PORT': 5432,
       }
    }
else:
    # development/test settings
    DEBUG = True
    cred_file = open(os.path.join(PROJECT_ROOT, 'local_config.json'))
    creds = json.load(cred_file)
    config = creds.get('CONFIG')
    SECRET_KEY = config.get("SECRET_KEY")
    ALLOWED_HOSTS = []
    DATABASES = {
       'default': {
           'ENGINE': 'django.db.backends.postgresql',
           'NAME': 'shubhamdipt',
       }
    }

'''########################################################################
#######                    Templating                                 #####
########################################################################'''

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            '{0}/templates/'.format(PROJECT_ROOT),
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.contrib.auth.context_processors.auth',
                'django.template.context_processors.debug',
                'django.template.context_processors.i18n',
                'django.template.context_processors.media',
                'django.template.context_processors.static',
                'django.template.context_processors.tz',
                'django.contrib.messages.context_processors.messages',
                'django.template.context_processors.request',
                'shubhamdipt.context_processors.global_settings',
            ],
        },
    },
]


'''########################################################################
#######             File Handling + Storage                           #####
########################################################################'''

STATICFILES_DIRS = (
    os.path.join(PROJECT_ROOT, 'static'),
)

STATIC_URL = '/static/'

STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles')


'''########################################################################
#######                    Caching                                    #####
########################################################################'''

# ToDo: Add Redis setup
open_redis_url = config.get('REDIS_URL')
if open_redis_url:
    CACHES = {
        'default': {
            'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
        }
    }
else:
    CACHES = {
        "default": {
            "BACKEND": "django_redis.cache.RedisCache",
            "LOCATION": open_redis_url,
            "OPTIONS": {
                "CLIENT_CLASS": "django_redis.client.DefaultClient",
                "IGNORE_EXCEPTIONS": True,
            },
            'KEY_PREFIX': DEP_NAME,
            'VERSION': VERSION,
            'TIMEOUT': 86400,  # 1 day
        },
    }

CACHING_MAX_AGE_BASIC = 60 * 60 * 24
SESSION_ENGINE = "django.contrib.sessions.backends.db"
# Cacheable files and compression support using whitenoise
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'


'''########################################################################
#######                     APIs + Other Tools                        #####
########################################################################'''

SUIT_CONFIG = {
    'ADMIN_NAME': 'Dr. Shubham Dipt',
    'MENU_EXCLUDE': ('auth.group', 'auth', 'site'),
    'MENU_OPEN_FIRST_CHILD': True
}

CRISPY_TEMPLATE_PACK = 'bootstrap3'


'''########################################################################
#######             Debug Toolbar settings                          #####
########################################################################'''

# Debug toolbar setting
if DEBUG:
    INTERNAL_IPS = ('127.0.0.1',)
    INSTALLED_APPS += (
        'debug_toolbar',
    )
    MIDDLEWARE_CLASSES += (
        'debug_toolbar.middleware.DebugToolbarMiddleware',
    )


'''########################################################################
#######                     Keys and Other Information               #####
########################################################################'''

# Sendwithus settings
EMAIL_TEMPLATE_LANGUAGES = {
    'de': 'de-DE',
    'en': 'en-US',
}
SENDWITHUS_API_KEY = config.get("SENDWITHUS_API_KEY", '')
# Cloudinary settings.
os.environ.setdefault("CLOUDINARY_URL", config.get('CLOUDINARY_URL', ''))
cloudinary.config(secure=True)  # use cloudinary always with SSL