Skip to content

Home Information - Your home, your data, organized.

Python

Improved Django settings and environment variable factoring.

Anthony Cassandrafcf3d923011d
diff --git a/.gitignore b/.gitignore
index 81098b4e..5cfcb3f8 100644
--- a/.gitignore
+++ b/.gitignore
@@ -17,6 +17,7 @@ __pycache__/
*.zip
*.Z
+/.private/
/venv/
/data/
/design/
diff --git a/deploy/env-generate.py b/deploy/env-generate.py
index dc71d640..a3015f8a 100755
--- a/deploy/env-generate.py
+++ b/deploy/env-generate.py
@@ -71,6 +71,11 @@ class HiEnvironmentGenerator:
SECRETS_DIRECTORY = '.private/env'
DEFAULT_ADMIN_EMAIL = '[email protected]'
+
+ DJANGO_SERVER_PORT_DEFAULT = '8000'
+ DJANGO_SERVER_PORT_MAP = {
+ 'development': '8411',
+ }
def __init__( self,
env_name : str = 'local',
@@ -92,9 +97,15 @@ class HiEnvironmentGenerator:
'HI_EMAIL_SUBJECT_PREFIX': '',
'HI_DB_PATH': '/data/database', # Location in Docker container
'HI_MEDIA_PATH': '/data/media', # location in Docker container
+ 'HI_EXTRA_HOST_URLS': '', # To be filled in manually if/when running beyond localhost
+ 'HI_EXTRA_CSP_URLS': '', # To be filled in manually if/when running beyond localhost
}
+ self._settings_map['DJANGO_SERVER_PORT'] = self.DJANGO_SERVER_PORT_MAP.get(
+ self._env_name,
+ self.DJANGO_SERVER_PORT_DEFAULT,
+ )
- if self._env_name not in [ 'development', 'local', 'production' ]:
+ if self._env_name not in [ 'local', 'production' ]:
self._settings_map['HI_REDIS_KEY_PREFIX'] = self._env_name
self._settings_map['HI_EMAIL_SUBJECT_PREFIX'] = f'[{self._env_name}] '
@@ -103,6 +114,13 @@ class HiEnvironmentGenerator:
def generate_env_file( self ):
+ self.print_important(
+ 'This script will help you generate your initial environment variables.'
+ '\nYou usually only need to run this once.'
+ '\nNone of the choices you make here are final.'
+ '\nYou can modify any of the settings directly in the generated file.'
+ )
+
self._setup_secrets_directory()
self._check_existing_env_file()
@@ -163,9 +181,9 @@ class HiEnvironmentGenerator:
def _get_email_settings( self ) -> EmailSettings:
- use_email = self.input_boolean( 'Configure to allow email alerts?', default = False )
+ use_email = self.input_boolean( 'Configure email to allow alert notifications?', default = False )
if use_email:
- self.print_notice( 'You may have to configure your email provider to allow this.' )
+ self.print_notice( 'You may have to tweak your email provider\'s settings to allow this.' )
else:
return EmailSettings(
email_address = self.DEFAULT_ADMIN_EMAIL,
@@ -324,9 +342,9 @@ class HiEnvironmentGenerator:
@staticmethod
def print_important( message : str ):
- border = '=' * (len(message) + 6)
+ border = '=' * ( min( len(message), 74 ) + 6)
print( f'\n\033[94m{border}\033[0m' ) # Blue border
- print( f'\033[94m {message} \033[0m' ) # Blue text
+ print( f'\033[94m{message}\033[0m' ) # Blue text
print( f'\033[94m{border}\033[0m\n' ) # Blue border
COMMON_EMAIL_PROVIDER_SETTINGS = {
diff --git a/packaging/docker_nginx.conf b/packaging/docker_nginx.conf
index 5262b9b3..450f497b 100644
--- a/packaging/docker_nginx.conf
+++ b/packaging/docker_nginx.conf
@@ -7,10 +7,6 @@ upstream wsgi_server {
server unix:/var/run/gunicorn.sock fail_timeout=0;
}
-upstream asgi_server {
- server unix:/var/run/daphne.sock fail_timeout=0;
-}
-
server {
listen 0.0.0.0:8000;
diff --git a/src/hi/settings/base.py b/src/hi/settings/base.py
index c41ae21e..719fae07 100644
--- a/src/hi/settings/base.py
+++ b/src/hi/settings/base.py
@@ -25,53 +25,45 @@ SECRET_KEY = env_settings.SECRET_KEY
DJANGO_SUPERUSER_EMAIL = env_settings.DJANGO_SUPERUSER_EMAIL
DJANGO_SUPERUSER_PASSWORD = env_settings.DJANGO_SUPERUSER_PASSWORD
-ALLOWED_HOSTS = (
- '127.0.0.1',
- 'localhost',
-)
+SITE_ID = env_settings.SITE_ID
+SITE_DOMAIN = env_settings.SITE_DOMAIN
+SITE_NAME = env_settings.SITE_NAME
+
+ALLOWED_HOSTS = env_settings.ALLOWED_HOSTS
+
+CORS_ALLOWED_ORIGINS = env_settings.CORS_ALLOWED_ORIGINS
-CORS_ALLOWED_ORIGINS = (
- 'http://127.0.0.1:8000',
- 'http://localhost:8000',
-)
CSP_DEFAULT_SRC = (
"'self'",
'data:',
- 'http://127.0.0.1:8000',
- 'http://localhost:8000',
-)
+) + env_settings.EXTRA_CSP_URLS
+
CSP_CONNECT_SRC = (
"'self'",
- 'http://127.0.0.1:8000',
- 'http://localhost:8000',
-)
+) + env_settings.EXTRA_CSP_URLS
+
CSP_FRAME_SRC = (
"'self'",
- 'http://127.0.0.1:8000',
- 'http://localhost:8000',
-)
+) + env_settings.EXTRA_CSP_URLS
CSP_SCRIPT_SRC = (
"'self'",
"'unsafe-inline'",
"'unsafe-eval'",
- 'http://127.0.0.1:8000',
- 'http://localhost:8000',
-)
+) + env_settings.EXTRA_CSP_URLS
+
CSP_STYLE_SRC = (
"'self'",
"'unsafe-inline'",
"'unsafe-eval'",
-)
+) + env_settings.EXTRA_CSP_URLS
CSP_MEDIA_SRC = (
"'self'",
"'unsafe-inline'",
"'unsafe-eval'",
'data:',
- 'http://127.0.0.1:8000',
- 'http://localhost:8000',
-)
+) + env_settings.EXTRA_CSP_URLS
CSP_IMG_SRC = (
"'self'",
@@ -312,8 +304,6 @@ SUPPRESS_AUTHENTICATION = env_settings.SUPPRESS_AUTHENTICATION
# ====================
# Transactional Emails
-SITE_DOMAIN = 'cassandra.org'
-
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_SUBJECT_PREFIX = "%s " % env_settings.EMAIL_SUBJECT_PREFIX
@@ -338,7 +328,7 @@ EMAIL_USE_SSL = env_settings.EMAIL_USE_SSL
# Needed when sending emails in background tasks since HttpRequest not
# available. Override this for development/testing/staging.
#
-BASE_URL_FOR_EMAIL_LINKS = 'https://{SITE_DOMAIN}'
+BASE_URL_FOR_EMAIL_LINKS = 'http://{SITE_DOMAIN}'
# ====================
diff --git a/src/hi/settings/development.py b/src/hi/settings/development.py
index 37f8f9e9..8800bad1 100644
--- a/src/hi/settings/development.py
+++ b/src/hi/settings/development.py
@@ -6,90 +6,6 @@ DEBUG = True
INSTALLED_APPS += [ 'hi.tests' ]
-ALLOWED_HOSTS = [
- '127.0.0.1',
- 'localhost',
- '192.168.100.6',
- 'groovy',
- '192.168.100.112',
- 'strudel',
-]
-
-# Content Security Policy Settings for CSPMiddleware
-#
-CORS_ALLOWED_ORIGINS = [
- 'http://127.0.0.1:8000',
- 'http://localhost:8000',
- 'http://192.168.100.6:8000',
- 'http://groovy:8000',
-]
-CSP_DEFAULT_SRC = (
- "'self'",
- 'data:',
- 'http://127.0.0.1:8000',
- 'http://localhost:8000',
- 'http://192.168.100.6:8000',
- 'http://groovy:8000',
-)
-CSP_CONNECT_SRC = (
- "'self'",
- 'http://127.0.0.1:8000',
- 'http://localhost:8000',
- 'http://192.168.100.6:8000',
- 'http://groovy:8000',
-)
-CSP_FRAME_SRC = [
- "'self'",
- 'http://127.0.0.1:8000',
- 'http://localhost:8000',
- 'http://192.168.100.6:8000',
- 'http://groovy:8000',
-]
-
-CSP_SCRIPT_SRC = (
- "'self'",
- "'unsafe-inline'",
- "'unsafe-eval'",
- 'http://127.0.0.1:8000',
- 'http://localhost:8000',
- 'http://192.168.100.6:8000',
- 'http://groovy:8000',
-
-
- 'https://bordeaux:8443',
-)
-CSP_STYLE_SRC = (
- "'self'",
- "'unsafe-inline'",
- "'unsafe-eval'",
-
- 'https://bordeaux:8443',
-)
-
-CSP_MEDIA_SRC = [
- "'self'",
- "'unsafe-inline'",
- "'unsafe-eval'",
- 'data:',
- 'http://192.168.100.6:8000',
- 'http://groovy:8000',
-]
-
-CSP_IMG_SRC = [
- "'self'",
- 'data:',
- 'https://bordeaux:8443',
-]
-
-CSP_CHILD_SRC = [
- "'self'",
-]
-
-CSP_FONT_SRC = [
- "'self'",
- 'data:',
-]
-
STATIC_ROOT = '/tmp/hi/static'
LOGGING = {
diff --git a/src/hi/settings/helpers.py b/src/hi/settings/helpers.py
index 8201c728..13d5fc09 100644
--- a/src/hi/settings/helpers.py
+++ b/src/hi/settings/helpers.py
@@ -13,10 +13,15 @@ class EnvironmentSettings:
Encapsulates the processing for the environment variables that are needed.
"""
DJANGO_SETTINGS_MODULE : str = ''
+ DJANGO_SERVER_PORT : int = 8000
SECRET_KEY : str = ''
DJANGO_SUPERUSER_EMAIL : str = None
DJANGO_SUPERUSER_PASSWORD : str = None
- EXTRA_ALLOWED_HOSTS : Tuple[ str ] = field( default_factory = tuple )
+ SITE_ID : str = 1
+ SITE_DOMAIN : str = 'localhost'
+ SITE_NAME : str = 'Home Information'
+ ALLOWED_HOSTS : Tuple[ str ] = field( default_factory = tuple )
+ CORS_ALLOWED_ORIGINS : Tuple[ str ] = field( default_factory = tuple )
EXTRA_CSP_URLS : Tuple[ str ] = field( default_factory = tuple )
DATABASES_NAME_PATH : str = ''
MEDIA_ROOT : str = ''
@@ -37,7 +42,7 @@ class EnvironmentSettings:
@classmethod
def get( cls ) -> 'EnvironmentSettings':
env_settings = EnvironmentSettings()
-
+
###########
# Core Django Settings
@@ -50,6 +55,12 @@ class EnvironmentSettings:
'DJANGO_SETTINGS_MODULE',
env_settings.DJANGO_SETTINGS_MODULE,
)
+ try:
+ env_settings.DJANGO_SERVER_PORT = int(
+ cls.get_env_variable( 'DJANGO_SERVER_PORT', required = False )
+ )
+ except ( TypeError, ValueError ):
+ pass
env_settings.SECRET_KEY = cls.get_env_variable(
'DJANGO_SECRET_KEY',
env_settings.SECRET_KEY,
@@ -62,34 +73,6 @@ class EnvironmentSettings:
'DJANGO_SUPERUSER_PASSWORD',
env_settings.DJANGO_SUPERUSER_PASSWORD )
- ###########
- # Extras to satisfy security requirements:
- # - Django strict host checking
- # - web browser CORS issues
-
- extra_host_list = list()
- extra_csp_url_list = list()
-
- extra_host_urls_str = cls.get_env_variable( 'HI_EXTRA_HOST_URLS' )
- if extra_host_urls_str:
- host_url_tuple_list = cls.parse_url_list_str( extra_host_urls_str )
- for host, url in host_url_tuple_list:
- extra_host_list.append( host )
- extra_csp_url_list.append( url )
- continue
-
- extra_csp_urls_str = cls.get_env_variable( 'HI_EXTRA_CSP_URLS' )
- if extra_csp_urls_str:
- host_url_tuple_list = cls.parse_url_list_str( extra_csp_urls_str )
- for host, url in host_url_tuple_list:
- extra_csp_url_list.append( url )
- continue
-
- if extra_host_list:
- env_settings.EXTRA_ALLOWED_HOSTS += tuple( extra_host_list )
- if extra_csp_url_list:
- env_settings.EXTRA_CSP_URLS += tuple( extra_csp_url_list )
-
###########
# Database and Media paths
@@ -165,6 +148,52 @@ class EnvironmentSettings:
env_settings.EMAIL_USE_SSL,
))
+ ###########
+ # Extras to satisfy security requirements:
+ # - Django strict host checking
+ # - web browser CORS/CSP issues
+
+ allowed_host_list = [
+ '127.0.0.1',
+ 'localhost',
+ ]
+ cors_allowed_origins_list = [
+ f'http://127.0.0.1:{env_settings.DJANGO_SERVER_PORT}',
+ f'http://localhost:{env_settings.DJANGO_SERVER_PORT}',
+ ]
+
+ extra_host_urls_str = cls.get_env_variable( 'HI_EXTRA_HOST_URLS' )
+ if extra_host_urls_str:
+ host_url_tuple_list = cls.parse_url_list_str( extra_host_urls_str )
+
+ # Assume first extra host is the SITE_DOMAIN, but this does not
+ # matter until Django "sites" feature need to be used (if
+ # ever).
+ #
+ if host_url_tuple_list:
+ env_settings.SITE_DOMAIN = host_url_tuple_list[0][0]
+
+ for host, url in host_url_tuple_list:
+
+ allowed_host_list.append( host )
+ cors_allowed_origins_list.append( url )
+ continue
+
+ extra_csp_urls_str = cls.get_env_variable( 'HI_EXTRA_CSP_URLS' )
+ if extra_csp_urls_str:
+ host_url_tuple_list = cls.parse_url_list_str( extra_csp_urls_str )
+ for host, url in host_url_tuple_list:
+ cors_allowed_origins_list.append( url )
+ continue
+
+ if allowed_host_list:
+ env_settings.ALLOWED_HOSTS += tuple( allowed_host_list )
+
+ # For now, forego any fine-grained control of the allowed urls for CORS and CSP
+ if cors_allowed_origins_list:
+ env_settings.CORS_ALLOWED_ORIGINS += tuple( cors_allowed_origins_list )
+ env_settings.EXTRA_CSP_URLS += tuple( cors_allowed_origins_list )
+
###########
# Application-specific
@@ -176,7 +205,7 @@ class EnvironmentSettings:
return env_settings
@classmethod
- def get_env_variable( cls, var_name, default = None ) -> str:
+ def get_env_variable( cls, var_name, default = None, required = True ) -> str:
try:
return os.environ[var_name]
except KeyError:
diff --git a/src/hi/settings/local.py b/src/hi/settings/local.py
index daea54a0..e60d8860 100644
--- a/src/hi/settings/local.py
+++ b/src/hi/settings/local.py
@@ -2,73 +2,6 @@ from .base import *
DEBUG = False
-SITE_DOMAIN = 'python-causal-kingfish.ngrok-free.app'
-
-ALLOWED_HOSTS = [
- '127.0.0.1',
- 'localhost',
- 'wordsacrossamerica.com',
- SITE_DOMAIN,
- '192.168.100.6',
-]
-
-CORS_ALLOWED_ORIGINS = [
- 'http://127.0.0.1:9411',
- 'http://localhost:9411',
-]
-CSP_DEFAULT_SRC = (
- "'self'",
- 'data:',
- 'http://127.0.0.1:8000',
- 'http://localhost:8000',
-)
-CSP_CONNECT_SRC = (
- "'self'",
- 'http://127.0.0.1:8000',
- 'http://localhost:8000',
-)
-CSP_FRAME_SRC = [
- "'self'",
- 'http://127.0.0.1:8000',
- 'http://localhost:8000',
-]
-
-CSP_SCRIPT_SRC = (
- "'self'",
- "'unsafe-inline'",
- "'unsafe-eval'",
- 'http://127.0.0.1:8000',
- 'http://localhost:8000',
-)
-CSP_STYLE_SRC = (
- "'self'",
- "'unsafe-inline'",
- "'unsafe-eval'",
-)
-
-CSP_MEDIA_SRC = [
- "'self'",
- "'unsafe-inline'",
- "'unsafe-eval'",
- 'data:',
- 'http://127.0.0.1:8000',
- 'http://localhost:8000',
-]
-
-CSP_IMG_SRC = [
- "'self'",
- 'data:',
-]
-
-CSP_CHILD_SRC = [
- "'self'",
-]
-
-CSP_FONT_SRC = [
- "'self'",
- 'data:',
-]
-
STATICFILES_STORAGE = 'pipeline.storage.PipelineManifestStorage'
STATIC_ROOT = '/src/static'
diff --git a/src/hi/settings/production.py b/src/hi/settings/production.py
index af3ad4a5..7e11d5b7 100644
--- a/src/hi/settings/production.py
+++ b/src/hi/settings/production.py
@@ -41,3 +41,5 @@ LOGGING = {
},
},
}
+
+BASE_URL_FOR_EMAIL_LINKS = 'https://{SITE_DOMAIN}'
diff --git a/src/manage.py b/src/manage.py
index 329a04e6..6c2915d9 100755
--- a/src/manage.py
+++ b/src/manage.py
@@ -25,26 +25,24 @@ def set_default_port_if_needed():
if ( len(sys.argv) < 2 ) or ( sys.argv[1] != "runserver" ):
return
- default_port_override = os.environ.get( 'DJANGO_DEV_PORT', 8000 )
+ default_port_override = os.environ.get( 'DJANGO_DEV_PORT' )
if not default_port_override:
return
- if has_hostname_only_arg():
+ if runserver_has_hostname_only_arg():
last_arg = sys.argv[-1]
new_last_arg = f'{last_arg}:{default_port_override}'
sys.argv[-1] = new_last_arg
- print( f'\nCHANGE: {new_last_arg}' )
return
- if not is_runserver_port_specified():
+ if not runserver_has_port_specified():
sys.argv.append( default_port_override )
- print( f'\nADD: {default_port_override}' )
return
return
-def has_hostname_only_arg():
+def runserver_has_hostname_only_arg():
if len(sys.argv) < 2 or sys.argv[1] != "runserver":
return False
if len(sys.argv) == 2:
@@ -62,7 +60,7 @@ def has_hostname_only_arg():
return False
-def is_runserver_port_specified() -> bool:
+def runserver_has_port_specified() -> bool:
"""Checks if a port is provided in the runserver command arguments."""
if len(sys.argv) < 2 or sys.argv[1] != "runserver":
return False