def test_email_url(self): a = dj_email_url.config() assert not a os.environ['EMAIL_URL'] = \ 'smtps://[email protected]:[email protected]:587' url = dj_email_url.config() assert url['EMAIL_BACKEND'] == \ 'django.core.mail.backends.smtp.EmailBackend' assert url['EMAIL_HOST'] == 'smtp.example.com' assert url['EMAIL_HOST_PASSWORD'] == 'password' assert url['EMAIL_HOST_USER'] == '*****@*****.**' assert url['EMAIL_PORT'] == 587 assert url['EMAIL_USE_TLS'] is True
def test_email_url(self): a = dj_email_url.config() assert not a os.environ['EMAIL_URL'] = \ 'smtps://[email protected]:[email protected]:587' url = dj_email_url.config() assert url['EMAIL_BACKEND'] == \ 'django.core.mail.backends.smtp.EmailBackend' assert url['EMAIL_HOST'] == 'smtp.example.com' assert url['EMAIL_HOST_PASSWORD'] == 'password' assert url['EMAIL_HOST_USER'] == '*****@*****.**' assert url['EMAIL_PORT'] == 587 assert url['EMAIL_USE_TLS'] is True assert url['EMAIL_USE_SSL'] is False
def factorise(): """ Returns a dict of settings suitable for Django, acquired from the environment in a 12factor-y way - see http://12factor.net/config Caller probably wants to, in `settings.py`: globals().update(factorise()) """ settings = {} settings['LOGGING'] = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'stdout': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', } }, 'loggers': { 'root': { 'handlers': ['stdout'], 'propagate': True, }, }, } settings['DATABASES'] = { 'default': dj_database_url.config(default='sqlite://:memory:') } settings['DEBUG'] = getenv_bool('DEBUG') if 'TEMPLATE_DEBUG' in os.environ: settings['TEMPLATE_DEBUG'] = getenv_bool('TEMPLATE_DEBUG') else: settings['TEMPLATE_DEBUG'] = settings['DEBUG'] # Slightly opinionated... if 'SECRET_KEY' in os.environ: settings['SECRET_KEY'] = os.environ['SECRET_KEY'] elif not settings['DEBUG']: sys.exit('DEBUG is False but no SECRET_KEY is set in the environment - either it has been hardcoded (bad) or not set at all (bad) - exit()ing for safety reasons') settings['CACHES'] = { 'default': django_cache_url.config(default='locmem://') } settings.update(dj_email_url.config(default='dummy://')) settings['ALLOWED_HOSTS'] = os.getenv('ALLOWED_HOSTS', '').split(',') return settings
def factorise(): """ Returns a dict of settings suitable for Django, acquired from the environment in a 12factor-y way - see http://12factor.net/config Caller probably wants to, in `settings.py`: globals().update(factorise()) """ settings = {} # Slightly opinionated... if 'SECRET_KEY' in os.environ: settings['SECRET_KEY'] = os.environ['SECRET_KEY'] else: logger.warn('No SECRET_KEY provided, using UUID') settings['SECRET_KEY'] = str(uuid.uuid4()) settings['LOGGING'] = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'stdout': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', } }, 'loggers': { 'root': { 'handlers': ['stdout'], 'propagate': True, }, }, } settings['DATABASES'] = { 'default': dj_database_url.config(default='sqlite://:memory:') # Note this'll currently break due to https://github.com/kennethreitz/dj-database-url/pull/21 } settings['DEBUG'] = getenv_bool('DEBUG') if 'TEMPLATE_DEBUG' in os.environ: settings['TEMPLATE_DEBUG'] = getenv_bool('TEMPLATE_DEBUG') else: settings['TEMPLATE_DEBUG'] = settings['DEBUG'] settings['CACHES'] = { 'default': django_cache_url.config(default='locmem://') } settings.update(dj_email_url.config(default='dummy://')) return settings
def configure_email(settings): s = settings import dj_email_url email_config = dj_email_url.config() if email_config: s.EMAIL_FILE_PATH = email_config['EMAIL_FILE_PATH'] s.EMAIL_HOST_USER = email_config['EMAIL_HOST_USER'] s.EMAIL_HOST_PASSWORD = email_config['EMAIL_HOST_PASSWORD'] s.EMAIL_HOST = email_config['EMAIL_HOST'] s.EMAIL_PORT = email_config['EMAIL_PORT'] s.EMAIL_BACKEND = email_config['EMAIL_BACKEND'] s.EMAIL_USE_TLS = email_config['EMAIL_USE_TLS'] else: s.EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' s.SERVER_EMAIL = env('SERVER_EMAIL', 'django@%s' % os.uname()[1]) s.DEFAULT_FROM_EMAIL = env('DEFAULT_FROM_EMAIL', '*****@*****.**')
def send_email(to, subject, content): email_config = dj_email_url.config() if not email_config: return smtp_config = {'host': email_config['EMAIL_HOST'], 'port': email_config['EMAIL_PORT'], 'login': email_config['EMAIL_HOST_USER'], 'password': email_config['EMAIL_HOST_PASSWORD'], 'tls': email_config['EMAIL_USE_TLS']} envelope = Envelope( from_addr='*****@*****.**', to_addr=[to], subject=subject, text_body=content) envelope.send(**smtp_config)
def send_email(to, subject, content): email_config = dj_email_url.config() if not email_config: return smtp_config = { 'host': email_config['EMAIL_HOST'], 'port': email_config['EMAIL_PORT'], 'login': email_config['EMAIL_HOST_USER'], 'password': email_config['EMAIL_HOST_PASSWORD'], 'tls': email_config['EMAIL_USE_TLS'] } envelope = Envelope(from_addr='*****@*****.**', to_addr=[to], subject=subject, text_body=content) envelope.send(**smtp_config)
def factorise(custom_settings=None): """ Return a dict of settings for Django, acquired from the environment. This is done in a 12factor-y way - see http://12factor.net/config Caller probably wants to, in `settings.py`: globals().update(factorise()) """ settings = {} settings['LOGGING'] = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'stdout': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', } }, 'root': { 'handlers': ['stdout'], }, } settings['DATABASES'] = { 'default': dj_database_url.config(default='sqlite://:memory:') } for (key, value) in six.iteritems(os.environ): _SUFFIX = "_DATABASE_URL" _OFFSET = len(_SUFFIX) if key.endswith(_SUFFIX): prefix = key[:-_OFFSET] if prefix != prefix.upper(): # i.e. it was not already all upper-cased logger.warn( "Not parsing %s as a database url because the " "prefix (%s) was not all upper-case - django12factor " "will convert prefixes to lower-case for use as database " "names" % (key, prefix)) continue dbname = key[:-_OFFSET].lower() if dbname == "default" and 'DATABASE_URL' in os.environ: logger.warn( "You have set the environment variables DATABASE_URL " "_and_ {key}, both of which would configure " "`DATABASES['default']`. {key} is being " "ignored.".format(key=key)) continue db = dj_database_url.parse(value) settings['DATABASES'][dbname] = db settings['DEBUG'] = getenv_bool('DEBUG') if 'TEMPLATE_DEBUG' in os.environ: settings['TEMPLATE_DEBUG'] = getenv_bool('TEMPLATE_DEBUG') else: settings['TEMPLATE_DEBUG'] = settings['DEBUG'] # Slightly opinionated... if 'SECRET_KEY' in os.environ: settings['SECRET_KEY'] = os.environ['SECRET_KEY'] elif not settings['DEBUG']: sys.exit("""DEBUG is False but no SECRET_KEY is set in the environment - either it has been hardcoded (bad) or not set at all (bad) - exit()ing for safety reasons""") settings['CACHES'] = { 'default': django_cache_url.config(default='locmem://') } settings.update(dj_email_url.config(default='dummy://')) settings['ALLOWED_HOSTS'] = os.getenv('ALLOWED_HOSTS', '').split(',') # For keys to different apis, etc. if custom_settings is None: custom_settings = [] for cs in custom_settings: settings[cs] = os.getenv(cs) return settings
ACCOUNT_DEFAULT_HTTP_PROTOCOL = "http" def get_local_ips(): import ifaddr for adapter in ifaddr.get_adapters(): for ip in adapter.ips: if isinstance(ip.ip, str): yield ip.ip ALLOWED_HOSTS.extend(get_local_ips()) # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases # See production.py for DATABASE_URL and EMAIL_URL format db_path = os.path.join(REPO_ROOT, f'db.sqlite3') DATABASES = { 'default': dj_database_url.config(default='sqlite:///' + db_path) } vars().update(dj_email_url.config(default='console://')) SESSION_ENGINE = 'django.contrib.sessions.backends.db' PRIVATE_STORAGE_SERVER = 'django' # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'z5b*=z^@^3e)3_y$f*s-0tt13jwczdjk*0aj$qefnt_b&u!)ee'
# def get_allowed_channels(request, channels): # if not request.user.is_authenticated(): # raise PermissionDenied('Not allowed to subscribe nor to publish on the Websocket!') # Use redis a session cache # https://github.com/martinrusev/django-redis-sessions # https://github.com/sebleier/django-redis-cache # http://michal.karzynski.pl/blog/2013/07/14/using-redis-as-django-session-store-and-cache-backend/ # pip install django-redis-sessions # # SESSION_ENGINE = 'redis_sessions.session' # SESSION_REDIS_PREFIX = 'session' FACILITY_WS4REDIS = 'frontend' email_config = dj_email_url.config() # if any(email_config): # EMAIL_FILE_PATH = email_config['EMAIL_FILE_PATH'] # EMAIL_HOST_USER = email_config['EMAIL_HOST_USER'] # EMAIL_HOST_PASSWORD = email_config['EMAIL_HOST_PASSWORD'] # EMAIL_HOST = email_config['EMAIL_HOST'] # EMAIL_PORT = email_config['EMAIL_PORT'] # EMAIL_BACKEND = email_config['EMAIL_BACKEND'] # EMAIL_USE_TLS = False # EMAIL_USE_SSL = True EMAIL_FILE_PATH = "" EMAIL_HOST_USER = "******" EMAIL_HOST_PASSWORD = "******" EMAIL_HOST = "smtpout.secureserver.net" EMAIL_PORT = 465
'default': dj_database_url.config('DATABASE_URL') } # Cache CACHES = { 'default': django_cache_url.config() } # Sessions SESSION_ENGINE = "django.contrib.sessions.backends.cache" SESSION_CACHE_ALIAS = "default" # Email DEFAULT_FROM_EMAIL = env('FROM_EMAIL') email_config = dj_email_url.config() EMAIL_FILE_PATH = email_config['EMAIL_FILE_PATH'] EMAIL_HOST_USER = email_config['EMAIL_HOST_USER'] EMAIL_HOST_PASSWORD = email_config['EMAIL_HOST_PASSWORD'] EMAIL_HOST = email_config['EMAIL_HOST'] EMAIL_PORT = email_config['EMAIL_PORT'] EMAIL_BACKEND = email_config['EMAIL_BACKEND'] EMAIL_USE_TLS = email_config['EMAIL_USE_TLS'] # Dates and times USE_TZ = True TIME_ZONE = 'UTC' # Internationalization LANGUAGE_CODE = 'en-us' USE_I18N = True
def factorise(custom_settings=None): """ Return a dict of settings for Django, acquired from the environment. This is done in a 12factor-y way - see http://12factor.net/config Caller probably wants to, in `settings.py`: globals().update(factorise()) """ settings = {} settings['LOGGING'] = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'stdout': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', } }, 'root': { 'handlers': ['stdout'], }, } settings['DATABASES'] = { 'default': dj_database_url.config(default='sqlite://:memory:') } settings['DEBUG'] = getenv_bool('DEBUG') if 'TEMPLATE_DEBUG' in os.environ: settings['TEMPLATE_DEBUG'] = getenv_bool('TEMPLATE_DEBUG') else: settings['TEMPLATE_DEBUG'] = settings['DEBUG'] # Slightly opinionated... if 'SECRET_KEY' in os.environ: settings['SECRET_KEY'] = os.environ['SECRET_KEY'] elif not settings['DEBUG']: sys.exit("""DEBUG is False but no SECRET_KEY is set in the environment - either it has been hardcoded (bad) or not set at all (bad) - exit()ing for safety reasons""") settings['CACHES'] = { 'default': django_cache_url.config(default='locmem://') } settings.update(dj_email_url.config(default='dummy://')) settings['ALLOWED_HOSTS'] = os.getenv('ALLOWED_HOSTS', '').split(',') # For keys to different apis, etc. if custom_settings is None: custom_settings = [] for cs in custom_settings: settings[cs] = os.getenv(cs) return settings
def __init__(self, email_url, receiver): self.config = dj_email_url.config(default=email_url) self.receiver = receiver
} ] WSGI_APPLICATION = "allodepute.wsgi.application" # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { "default": dj_database_url.config( default="postgis://*****:*****@localhost/allodepute" ) } # SMTP email_config = dj_email_url.config(default="smtp://localhost/") EMAIL_FILE_PATH = email_config["EMAIL_FILE_PATH"] EMAIL_HOST_USER = email_config["EMAIL_HOST_USER"] EMAIL_HOST_PASSWORD = email_config["EMAIL_HOST_PASSWORD"] EMAIL_HOST = email_config["EMAIL_HOST"] EMAIL_PORT = email_config["EMAIL_PORT"] EMAIL_BACKEND = email_config["EMAIL_BACKEND"] EMAIL_USE_TLS = email_config["EMAIL_USE_TLS"] EMAIL_USE_SSL = email_config["EMAIL_USE_SSL"] # Password validation # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
DATABASES = { # db config from DATABASE_URL env variable; e.g.: # mysql://itec:[email protected]:3306/itec_dev_2018 # sqlite:///tmp/db.sqlite3 'default': dj_database_url.config(conn_max_age=600) } SESSION_ENGINE = 'django.contrib.sessions.backends.cache' SESSION_CACHE_ALIAS = 'session' for engine in TEMPLATES: if 'loaders' in engine and not engine.get('debug', DEBUG): engine['loaders'] = [('django.template.loaders.cached.Loader', engine['loaders'])] # e-mail config from EMAIL_URL env variable; e.g.: # console:// - print to stdout # smtp://mailhog.ligaac.ro:1025 - unencrypted and unauthenticated smtp # smtp:// - send via local MTA (sendmail, postfix, etc) # submit://sendgrid_username:[email protected] - port 587 with STARTTLS # smtp://[email protected]:[email protected]:465/?ssl=True - port 465 with SSL vars().update(dj_email_url.config()) DEFAULT_FROM_EMAIL = getenv_assert('EMAIL_FROM') EMAIL_SUBJECT_PREFIX = os.getenv('EMAIL_SUBJECT_PREFIX', "") SILENCED_SYSTEM_CHECKS = [ 'security.W004', # SECURE_HSTS_SECONDS 'security.W008', # SECURE_SSL_REDIRECT ]
'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ] ROOT_URLCONF = 'variant-kb.urls' DATETIME_FORMAT = DATE_FORMAT = os.getenv('DATE_FORMAT', 'N j, Y') # User & Email Settings AUTH_USER_MODEL = 'accounts.User' LOGIN_REDIRECT_URL = '/' EMAIL = { 'default': dj_email_url.config(default=os.getenv( 'SENDGRID_URL', 'smtps://[email protected]:[email protected]:587')), } # EMAIL_HOST_PASSWORD = os.getenv('SENDGRID_API_KEY', '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') # Templates TEMPLATES = [{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(os.getenv('BASE_DIR', ''), 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages',
], }, }, ] WSGI_APPLICATION = 'verbes.wsgi.application' # Database # https://docs.djangoproject.com/en/dev/ref/settings/#databases DATABASES = { 'default': dj_database_url.parse(url=os.environ['DATABASE_URL']) } vars().update(dj_email_url.config()) # Password validation # https://docs.djangoproject.com/en/dev/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, {
'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.media', 'django.template.context_processors.csrf', 'django.template.context_processors.tz', 'django.template.context_processors.i18n', 'django_settings_export.settings_export', 'cms.context_processors.cms_settings', 'sekizai.context_processors.sekizai', ], }, }, ] # translating the EMAIL_URL env var into django email settings email_config = dj_email_url.config(env="EMAIL_URL", default="console:") vars().update( email_config ) # this loads the standard django email settings such as EMAIL_HOST, etc. # EMAIL_FROM should be included in the EMAIL_URL, see https://github.com/migonzalvar/dj-email-url#set-from-email-addresses SERVER_EMAIL = email_config.get('SERVER_EMAIL', 'root@localhost') DEFAULT_FROM_EMAIL = email_config.get('DEFAULT_FROM_EMAIL', f'{SITE_NAME} <info@{DOMAIN}>') if DJANGO_ENV == DjangoEnv.LOCAL: CACHE_URL = 'dummy://' # to disable a warning from aldryn-django # avoid locmem as default on production, it doesn't work properly CACHES = {'default': django_cache_url.config(default="dummy://")}
def factorise(custom_settings=None): """ Return a dict of settings for Django, acquired from the environment. This is done in a 12factor-y way - see http://12factor.net/config Caller probably wants to, in `settings.py`: globals().update(factorise()) """ settings = {} settings['LOGGING'] = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'stdout': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', } }, 'root': { 'handlers': ['stdout'], }, } settings['DATABASES'] = { 'default': dj_database_url.config(default='sqlite://:memory:') } for (key, value) in six.iteritems(os.environ): _SUFFIX = "_DATABASE_URL" _OFFSET = len(_SUFFIX) if key.endswith(_SUFFIX): prefix = key[:-_OFFSET] if prefix != prefix.upper(): # i.e. it was not already all upper-cased logger.warn( "Not parsing %s as a database url because the " "prefix (%s) was not all upper-case - django12factor " "will convert prefixes to lower-case for use as database " "names" % (key, prefix)) continue dbname = key[:-_OFFSET].lower() if dbname == "default" and 'DATABASE_URL' in os.environ: logger.warn( "You have set the environment variables DATABASE_URL " "_and_ {key}, both of which would configure " "`DATABASES['default']`. {key} is being " "ignored.".format(key=key)) continue db = dj_database_url.parse(value) settings['DATABASES'][dbname] = db settings['DEBUG'] = getenv_bool('DEBUG') if 'TEMPLATE_DEBUG' in os.environ: settings['TEMPLATE_DEBUG'] = getenv_bool('TEMPLATE_DEBUG') else: settings['TEMPLATE_DEBUG'] = settings['DEBUG'] # Slightly opinionated... if 'SECRET_KEY' in os.environ: settings['SECRET_KEY'] = os.environ['SECRET_KEY'] elif not settings['DEBUG']: sys.exit( """DEBUG is False but no SECRET_KEY is set in the environment - either it has been hardcoded (bad) or not set at all (bad) - exit()ing for safety reasons""") settings['CACHES'] = { 'default': django_cache_url.config(default='locmem://') } settings.update(dj_email_url.config(default='dummy://')) settings['ALLOWED_HOSTS'] = os.getenv('ALLOWED_HOSTS', '').split(',') # For keys to different apis, etc. if custom_settings is None: custom_settings = [] for cs in custom_settings: settings[cs] = os.getenv(cs) return settings
{ 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True EMAIL_CONFIG = dj_email_url.config() """ STATIC ASSET HANDLING - WhiteNoise configuration for forever-cacheable files and compression support """ STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ]