Skip to content

Home Information - Your home, your data, organized.

Python

Added 8411 as default runserver port. Refactor env var parsing.

Anthony Cassandra5cb8437e7662
diff --git a/src/custom/management/commands/hi_creategroups.py b/src/custom/management/commands/hi_creategroups.py
index 73e96607..daeb8be1 100644
--- a/src/custom/management/commands/hi_creategroups.py
+++ b/src/custom/management/commands/hi_creategroups.py
@@ -3,13 +3,13 @@ from django.core.management.base import BaseCommand
from django.contrib.auth.models import Group
-class Command(BaseCommand):
+class Command( BaseCommand ):
"""
Command provided so that we can automate creating groups we need
for the game, mostly around tools and content management administrative
functions.
"""
- def handle(self, *args, **options):
+ def handle( self, *args, **options ):
# TODO: Placeholder for eventual groups creation.
return
diff --git a/src/custom/management/commands/hi_createsuperuser.py b/src/custom/management/commands/hi_createsuperuser.py
index 412e0001..62f214ac 100644
--- a/src/custom/management/commands/hi_createsuperuser.py
+++ b/src/custom/management/commands/hi_createsuperuser.py
@@ -4,13 +4,13 @@ from django.core.management.base import BaseCommand
from custom.models import CustomUser
-class Command(BaseCommand):
+class Command( BaseCommand ):
"""
Command provided so that we can automate creating the super user in
deployments. Normal django "createsuperuser" does not allow pasing
password.
"""
- def handle(self, *args, **options):
+ def handle( self, *args, **options ):
admin_email = settings.DJANGO_SUPERUSER_EMAIL
admin_password = settings.DJANGO_SUPERUSER_PASSWORD
if not admin_email or not admin_password:
diff --git a/src/hi/settings/base.py b/src/hi/settings/base.py
index bac67e6c..c41ae21e 100644
--- a/src/hi/settings/base.py
+++ b/src/hi/settings/base.py
@@ -13,72 +13,43 @@ https://docs.djangoproject.com/en/4.2/ref/settings/
from pathlib import Path
import os
-from django.core.exceptions import ImproperlyConfigured
-
-
-def get_env_variable( var_name, default=None ):
- try:
- return os.environ[var_name]
- except KeyError:
- if default:
- return default
- error_msg = "Set the %s environment variable" % var_name
- raise ImproperlyConfigured(error_msg)
+from .helpers import EnvironmentSettings
+env_settings = EnvironmentSettings.get()
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
-SECRET_KEY = get_env_variable('DJANGO_SECRET_KEY')
+SECRET_KEY = env_settings.SECRET_KEY
-DJANGO_SUPERUSER_EMAIL = get_env_variable( 'DJANGO_SUPERUSER_EMAIL', None )
-DJANGO_SUPERUSER_PASSWORD = get_env_variable( 'DJANGO_SUPERUSER_PASSWORD', None )
-
-AUTH_USER_MODEL = "custom.CustomUser"
-SUPPRESS_AUTHENTICATION = bool( get_env_variable( 'HI_SUPPRESS_AUTHENTICATION', 'false' ) == 'true' )
+DJANGO_SUPERUSER_EMAIL = env_settings.DJANGO_SUPERUSER_EMAIL
+DJANGO_SUPERUSER_PASSWORD = env_settings.DJANGO_SUPERUSER_PASSWORD
-ALLOWED_HOSTS = [
+ALLOWED_HOSTS = (
'127.0.0.1',
- '192.168.100.2',
- '192.168.100.4',
- '192.168.100.6',
'localhost',
-]
+)
-CORS_ALLOWED_ORIGINS = [
+CORS_ALLOWED_ORIGINS = (
'http://127.0.0.1:8000',
'http://localhost:8000',
- 'http://192.168.100.2:8111',
- 'http://192.168.100.4:8111',
- 'http://192.168.100.6:8111',
-]
+)
CSP_DEFAULT_SRC = (
"'self'",
'data:',
'http://127.0.0.1:8000',
'http://localhost:8000',
- 'http://192.168.100.2:8111',
- 'http://192.168.100.4:8111',
- 'http://192.168.100.6:8111',
)
CSP_CONNECT_SRC = (
"'self'",
'http://127.0.0.1:8000',
'http://localhost:8000',
- 'http://192.168.100.6:8111',
- "ws://127.0.0.1:8000",
- "ws://localhost:8000",
- 'ws://192.168.100.6:8111',
- 'ws://192.168.100.80:8000',
- )
-CSP_FRAME_SRC = [
+)
+CSP_FRAME_SRC = (
"'self'",
'http://127.0.0.1:8000',
'http://localhost:8000',
- 'http://192.168.100.2:8111',
- 'http://192.168.100.4:8111',
- 'http://192.168.100.6:8111',
-]
+)
CSP_SCRIPT_SRC = (
"'self'",
@@ -86,9 +57,6 @@ CSP_SCRIPT_SRC = (
"'unsafe-eval'",
'http://127.0.0.1:8000',
'http://localhost:8000',
- 'http://192.168.100.2:8111',
- 'http://192.168.100.4:8111',
- 'http://192.168.100.6:8111',
)
CSP_STYLE_SRC = (
"'self'",
@@ -96,31 +64,28 @@ CSP_STYLE_SRC = (
"'unsafe-eval'",
)
-CSP_MEDIA_SRC = [
+CSP_MEDIA_SRC = (
"'self'",
"'unsafe-inline'",
"'unsafe-eval'",
'data:',
'http://127.0.0.1:8000',
'http://localhost:8000',
- 'http://192.168.100.2:8111',
- 'http://192.168.100.4:8111',
- 'http://192.168.100.6:8111',
-]
+)
-CSP_IMG_SRC = [
+CSP_IMG_SRC = (
"'self'",
'data:',
-]
+)
-CSP_CHILD_SRC = [
+CSP_CHILD_SRC = (
"'self'",
-]
+)
-CSP_FONT_SRC = [
+CSP_FONT_SRC = (
"'self'",
'data:',
-]
+)
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
@@ -206,12 +171,10 @@ WSGI_APPLICATION = 'hi.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases
-HI_DB_PATH = get_env_variable('HI_DB_PATH')
-
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
- 'NAME': os.path.join( HI_DB_PATH, 'hi.sqlite3' ),
+ 'NAME': os.path.join( env_settings.DATABASES_NAME_PATH, 'hi.sqlite3' ),
}
}
@@ -261,7 +224,7 @@ STATICFILES_DIRS = (
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
-MEDIA_ROOT = get_env_variable('HI_MEDIA_PATH')
+MEDIA_ROOT = env_settings.MEDIA_ROOT
MEDIA_URL = '/media/'
PIPELINE = {
@@ -327,9 +290,9 @@ CONSTANCE_CONFIG = {
'DOWN_FOR_MAINTENANCE': ( False, 'Should we force the down for maintenance page to show?' ),
}
-REDIS_HOST = get_env_variable('HI_REDIS_HOST')
-REDIS_PORT = int(get_env_variable('HI_REDIS_PORT'))
-REDIS_KEY_PREFIX = get_env_variable('HI_REDIS_KEY_PREFIX')
+REDIS_HOST = env_settings.REDIS_HOST
+REDIS_PORT = env_settings.REDIS_PORT
+REDIS_KEY_PREFIX = env_settings.REDIS_KEY_PREFIX
CACHES = {
'default': {
@@ -342,44 +305,46 @@ CACHES = {
}
}
-#====================
+
+AUTH_USER_MODEL = "custom.CustomUser"
+SUPPRESS_AUTHENTICATION = env_settings.SUPPRESS_AUTHENTICATION
+
+# ====================
# Transactional Emails
SITE_DOMAIN = 'cassandra.org'
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
-EMAIL_SUBJECT_PREFIX = "%s " % get_env_variable('HI_EMAIL_SUBJECT_PREFIX')
-DEFAULT_FROM_EMAIL = get_env_variable('HI_DEFAULT_FROM_EMAIL')
-SERVER_EMAIL = get_env_variable('HI_SERVER_EMAIL')
+EMAIL_SUBJECT_PREFIX = "%s " % env_settings.EMAIL_SUBJECT_PREFIX
+DEFAULT_FROM_EMAIL = env_settings.DEFAULT_FROM_EMAIL
+SERVER_EMAIL = env_settings.SERVER_EMAIL
FROM_EMAIL_NAME = "Home Information"
# Normal Settings
-EMAIL_HOST = get_env_variable('HI_EMAIL_HOST')
+EMAIL_HOST = env_settings.EMAIL_HOST
try:
- EMAIL_PORT = int(get_env_variable('HI_EMAIL_PORT'))
+ EMAIL_PORT = env_settings.EMAIL_PORT
except (TypeError, ValueError):
EMAIL_PORT = 587
-EMAIL_HOST_USER = get_env_variable('HI_EMAIL_HOST_USER')
-EMAIL_HOST_PASSWORD = get_env_variable('HI_EMAIL_HOST_PASSWORD')
+EMAIL_HOST_USER = env_settings.EMAIL_HOST_USER
+EMAIL_HOST_PASSWORD = env_settings.EMAIL_HOST_PASSWORD
EMAIL_TIMEOUT = 10 # In seconds
-if get_env_variable('HI_EMAIL_USE_TLS').lower() == 'true':
- EMAIL_USE_TLS = True
- EMAIL_USE_SSL = False
-elif get_env_variable('HI_EMAIL_USE_SSL').lower() == 'true':
- EMAIL_USE_TLS = False
- EMAIL_USE_SSL = True
-else:
- EMAIL_USE_TLS = False
- EMAIL_USE_SSL = False
+EMAIL_USE_TLS = env_settings.EMAIL_USE_TLS
+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}'
+
+# ====================
+# Development-related Settings
+# (override in development.py, not here)
+
# When tests functionality requires knowing if in unit test context.
UNIT_TESTING = False
diff --git a/src/hi/settings/development.py b/src/hi/settings/development.py
index b2ee44ed..37f8f9e9 100644
--- a/src/hi/settings/development.py
+++ b/src/hi/settings/development.py
@@ -8,9 +8,11 @@ INSTALLED_APPS += [ 'hi.tests' ]
ALLOWED_HOSTS = [
'127.0.0.1',
+ 'localhost',
'192.168.100.6',
+ 'groovy',
'192.168.100.112',
- 'localhost',
+ 'strudel',
]
# Content Security Policy Settings for CSPMiddleware
@@ -18,31 +20,30 @@ ALLOWED_HOSTS = [
CORS_ALLOWED_ORIGINS = [
'http://127.0.0.1:8000',
'http://localhost:8000',
- 'http://192.168.100.6:8008',
+ '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:8008',
+ '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:8008',
- "ws://127.0.0.1:8000",
- "ws://localhost:8000",
- 'ws://192.168.100.6:8008',
- 'ws://192.168.100.80: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:8008',
- 'https://player.vimeo.com',
+ 'http://192.168.100.6:8000',
+ 'http://groovy:8000',
]
CSP_SCRIPT_SRC = (
@@ -51,13 +52,18 @@ CSP_SCRIPT_SRC = (
"'unsafe-eval'",
'http://127.0.0.1:8000',
'http://localhost:8000',
- 'http://192.168.100.6:8008',
+ '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 = [
@@ -65,10 +71,8 @@ CSP_MEDIA_SRC = [
"'unsafe-inline'",
"'unsafe-eval'",
'data:',
- 'http://127.0.0.1:8000',
- 'http://localhost:8000',
- 'http://192.168.100.6:8008',
- 'https://bordeaux:8443',
+ 'http://192.168.100.6:8000',
+ 'http://groovy:8000',
]
CSP_IMG_SRC = [
diff --git a/src/hi/settings/helpers.py b/src/hi/settings/helpers.py
new file mode 100644
index 00000000..8201c728
--- /dev/null
+++ b/src/hi/settings/helpers.py
@@ -0,0 +1,231 @@
+from dataclasses import dataclass, field
+import os
+import re
+from typing import Tuple
+import urllib.parse
+
+from django.core.exceptions import ImproperlyConfigured
+
+
+@dataclass
+class EnvironmentSettings:
+ """
+ Encapsulates the processing for the environment variables that are needed.
+ """
+ DJANGO_SETTINGS_MODULE : str = ''
+ SECRET_KEY : str = ''
+ DJANGO_SUPERUSER_EMAIL : str = None
+ DJANGO_SUPERUSER_PASSWORD : str = None
+ EXTRA_ALLOWED_HOSTS : Tuple[ str ] = field( default_factory = tuple )
+ EXTRA_CSP_URLS : Tuple[ str ] = field( default_factory = tuple )
+ DATABASES_NAME_PATH : str = ''
+ MEDIA_ROOT : str = ''
+ REDIS_HOST : str = ''
+ REDIS_PORT : int = 6379
+ REDIS_KEY_PREFIX : str = ''
+ SUPPRESS_AUTHENTICATION : bool = True
+ EMAIL_SUBJECT_PREFIX : str = ''
+ DEFAULT_FROM_EMAIL : str = ''
+ SERVER_EMAIL : str = ''
+ EMAIL_HOST : str = ''
+ EMAIL_PORT : int = 587
+ EMAIL_HOST_USER : str = ''
+ EMAIL_HOST_PASSWORD : str = ''
+ EMAIL_USE_TLS : bool = False
+ EMAIL_USE_SSL : bool = False
+
+ @classmethod
+ def get( cls ) -> 'EnvironmentSettings':
+ env_settings = EnvironmentSettings()
+
+ ###########
+ # Core Django Settings
+
+ # DJANGO_SETTINGS_MODULE is parsed by Django before this module
+ # ever executes. We include it here for completeness so there is
+ # one place to see all env vars required, but it is not used by the
+ # application code itself.
+ #
+ env_settings.DJANGO_SETTINGS_MODULE = cls.get_env_variable(
+ 'DJANGO_SETTINGS_MODULE',
+ env_settings.DJANGO_SETTINGS_MODULE,
+ )
+ env_settings.SECRET_KEY = cls.get_env_variable(
+ 'DJANGO_SECRET_KEY',
+ env_settings.SECRET_KEY,
+ )
+ env_settings.DJANGO_SUPERUSER_EMAIL = cls.get_env_variable(
+ 'DJANGO_SUPERUSER_EMAIL',
+ env_settings.DJANGO_SUPERUSER_EMAIL,
+ )
+ env_settings.DJANGO_SUPERUSER_PASSWORD = cls.get_env_variable(
+ '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
+
+ env_settings.DATABASES_NAME_PATH = cls.get_env_variable(
+ 'HI_DB_PATH',
+ env_settings.DATABASES_NAME_PATH,
+ )
+ env_settings.MEDIA_ROOT = cls.get_env_variable(
+ 'HI_MEDIA_PATH',
+ env_settings.MEDIA_ROOT,
+ )
+
+ ###########
+ # Redis
+
+ env_settings.REDIS_HOST = cls.get_env_variable(
+ 'HI_REDIS_HOST',
+ env_settings.REDIS_HOST,
+ )
+ try:
+ env_settings.REDIS_PORT = int( cls.get_env_variable('HI_REDIS_PORT') )
+ except ( TypeError, ValueError ):
+ pass
+ env_settings.REDIS_KEY_PREFIX = cls.get_env_variable(
+ 'HI_REDIS_KEY_PREFIX',
+ env_settings.REDIS_KEY_PREFIX,
+
+ )
+
+ ###########
+ # Email-related
+
+ env_settings.EMAIL_SUBJECT_PREFIX = "%s " % cls.get_env_variable(
+ 'HI_EMAIL_SUBJECT_PREFIX',
+ env_settings.EMAIL_SUBJECT_PREFIX,
+ )
+ env_settings.DEFAULT_FROM_EMAIL = cls.get_env_variable(
+ 'HI_DEFAULT_FROM_EMAIL',
+ env_settings.DEFAULT_FROM_EMAIL,
+ )
+ env_settings.SERVER_EMAIL = cls.get_env_variable(
+ 'HI_SERVER_EMAIL',
+ env_settings.SERVER_EMAIL,
+ )
+ env_settings.EMAIL_HOST = cls.get_env_variable(
+ 'HI_EMAIL_HOST',
+ env_settings.EMAIL_HOST,
+ )
+ try:
+ env_settings.EMAIL_PORT = int( cls.get_env_variable(
+ 'HI_EMAIL_PORT',
+ env_settings.EMAIL_PORT,
+ ))
+ except ( TypeError, ValueError ):
+ pass
+ env_settings.EMAIL_HOST_USER = cls.get_env_variable(
+ 'HI_EMAIL_HOST_USER',
+ env_settings.EMAIL_HOST_USER,
+ )
+ env_settings.EMAIL_HOST_PASSWORD = cls.get_env_variable(
+ 'HI_EMAIL_HOST_PASSWORD',
+ env_settings.EMAIL_HOST_PASSWORD,
+ )
+ env_settings.EMAIL_USE_TLS = cls.to_bool( cls.get_env_variable(
+ 'HI_EMAIL_USE_TLS',
+ env_settings.EMAIL_USE_TLS,
+ ))
+ if env_settings.EMAIL_USE_TLS:
+ env_settings.EMAIL_USE_SSL = False
+ else:
+ env_settings.EMAIL_USE_SSL = cls.to_bool( cls.get_env_variable(
+ 'HI_EMAIL_USE_SSL',
+ env_settings.EMAIL_USE_SSL,
+ ))
+
+ ###########
+ # Application-specific
+
+ env_settings.SUPPRESS_AUTHENTICATION = cls.to_bool( cls.get_env_variable(
+ 'HI_SUPPRESS_AUTHENTICATION',
+ env_settings.SUPPRESS_AUTHENTICATION,
+ ))
+
+ return env_settings
+
+ @classmethod
+ def get_env_variable( cls, var_name, default = None ) -> str:
+ try:
+ return os.environ[var_name]
+ except KeyError:
+ if default:
+ return default
+ error_msg = "Set the %s environment variable" % var_name
+ raise ImproperlyConfigured(error_msg)
+
+ @classmethod
+ def to_bool( cls, value: object ) -> bool:
+ if isinstance( value, bool ):
+ return value
+ if isinstance( value, str ):
+ truthy_values = {'true', '1', 'on', 'yes', 'y', 't', 'enabled'}
+ if isinstance( value, str ):
+ return value.strip().lower() in truthy_values
+ return False
+ return bool( value )
+
+ @classmethod
+ def parse_url_list_str( cls, a_string : str ):
+ url_str_list = re.split( r'[\s\;\,]+', a_string )
+ host_url_tuple_list = list()
+ for url_str in url_str_list:
+ try:
+ parsed_url = cls.parse_url( url_str )
+ scheme = parsed_url.scheme
+ host = parsed_url.hostname
+ port = parsed_url.port
+ if port:
+ normalized_url_str = f'{scheme}://{host}:{port}'
+ else:
+ normalized_url_str = f'{scheme}://{host}'
+ host_url_tuple_list.append( ( host, normalized_url_str ) )
+
+ except ( TypeError, ValueError ):
+ pass
+ continue
+ return host_url_tuple_list
+
+ @classmethod
+ def parse_url( cls, url_str : str ) -> urllib.parse.ParseResult:
+ if not url_str:
+ raise ValueError()
+ try:
+ parsed_url = urllib.parse.urlparse( url_str )
+ if not ( parsed_url.scheme and parsed_url.netloc ):
+ raise ValueError()
+ return parsed_url
+ except TypeError:
+ pass
+ raise ValueError()
diff --git a/src/hi/settings/local.py b/src/hi/settings/local.py
index e60d8860..daea54a0 100644
--- a/src/hi/settings/local.py
+++ b/src/hi/settings/local.py
@@ -2,6 +2,73 @@ 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/simulator.py b/src/hi/settings/simulator.py
index 84f26092..d75a37b8 100644
--- a/src/hi/settings/simulator.py
+++ b/src/hi/settings/simulator.py
@@ -36,7 +36,7 @@ ROOT_URLCONF = 'hi.simulator.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
- 'DIRS': [ os.path.join(BASE_DIR, "templates") ],
+ 'DIRS': [ os.path.join( BASE_DIR, "templates") ],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
@@ -53,6 +53,6 @@ TEMPLATES = [
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
- 'NAME': os.path.join( HI_DB_PATH, 'simulator.sqlite3' ),
+ 'NAME': os.path.join( env_settings.DATABASES_NAME_PATH, 'simulator.sqlite3' ),
}
}
diff --git a/src/manage.py b/src/manage.py
index 692ac7f2..329a04e6 100755
--- a/src/manage.py
+++ b/src/manage.py
@@ -1,6 +1,7 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
+import re
import sys
@@ -15,7 +16,65 @@ def main():
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
- execute_from_command_line(sys.argv)
+
+ set_default_port_if_needed() # HI Customization
+ execute_from_command_line( sys.argv )
+
+
+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 )
+ if not default_port_override:
+ return
+
+ if 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():
+ sys.argv.append( default_port_override )
+ print( f'\nADD: {default_port_override}' )
+ return
+
+ return
+
+
+def has_hostname_only_arg():
+ if len(sys.argv) < 2 or sys.argv[1] != "runserver":
+ return False
+ if len(sys.argv) == 2:
+ return False
+
+ last_arg = sys.argv[-1]
+ if last_arg.startswith( '--' ):
+ return False
+ if re.fullmatch( r'\d+', last_arg ):
+ return False
+ if re.fullmatch( r'\d+\.\d+\.\d+\.\d+', last_arg ):
+ return True
+ if re.fullmatch( r'[a-zA-Z0-9_][a-zA-Z0-9\-_\.]+', last_arg ):
+ return True
+ return False
+
+
+def is_runserver_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
+
+ for arg in sys.argv[2:]:
+ if arg.startswith("--"):
+ continue
+ if re.fullmatch( r'\d{4,5}', arg ) or re.fullmatch( r'[\d\.]+:\d{4,5}', arg ):
+ return True
+ continue
+
+ return False
if __name__ == '__main__':
diff --git a/src/simulator.py b/src/simulator.py
index d55c7a33..fd9a5efd 100755
--- a/src/simulator.py
+++ b/src/simulator.py
@@ -27,7 +27,7 @@ def main():
command_args = sys.argv[2:]
if command == "runserver":
if not any( arg.isdigit() for arg in command_args ):
- command_args.append( "8001" )
+ command_args.append( "7411" )
full_command = [ 'python', manage_py_path, command ] + command_args + [ f'--settings={settings_module}' ]
result = run( full_command )