3.1. Settings About
local_settings.py
Environmental variables settings
.env file
Docker/Kubernetes secrets
Heroku env variables
Debug Toolbar
3.1.1. Default Settings
"""
Django settings for myproject project.
Generated by 'django-admin startproject' using Django 5.0.4.
For more information on this file, see
https://docs.djangoproject.com/en/5.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/5.0/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-#ire!x%o$%it-6dp@14ux@zmcpq*np%zqt^si_u$cq*gy)fr3j'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'myproject.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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 = 'myproject.wsgi.application'
# Database
# https://docs.djangoproject.com/en/5.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/5.0/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',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/5.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.0/howto/static-files/
STATIC_URL = 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
3.1.2. Use Case - 1
import os
from datetime import timedelta, datetime, timezone
from django.conf.locale.en import formats as en_formats
from django.core.exceptions import ImproperlyConfigured
# Load settings from system environment variables
try:
DEBUG = os.environ.get('DJANGO_DEBUG', False)
DEBUG_TOOLBAR = os.environ.get('DJANGO_DEBUG_TOOLBAR', False)
SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', 'this_is_default_key_please_change_it_using_env_variable')
ALLOWED_HOST = os.environ.get('DJANGO_ALLOWED_HOST', 'localhost')
SECURE_SSL_REDIRECT = os.environ.get('DJANGO_ALWAYS_HTTPS', False)
# Make sure, you also change conf/nginx.conf
MEDIA_ROOT = os.environ.get('DJANGO_MEDIA_ROOT', '/tmp/media')
STATIC_ROOT = os.environ.get('DJANGO_STATIC_ROOT', '/tmp/static')
MEDIA_URL = os.environ.get('DJANGO_MEDIA_URL', '/media/')
STATIC_URL = os.environ.get('DJANGO_STATIC_URL', '/static/')
DATABASE_ENGINE = os.environ.get('DATABASE_ENGINE', 'django.db.backends.sqlite3')
DATABASE_HOST = os.environ.get('DATABASE_HOST', None)
DATABASE_PORT = os.environ.get('DATABASE_PORT', None)
DATABASE_NAME = os.environ.get('DATABASE_NAME', '/tmp/myproject/db.sqlite3')
DATABASE_USER = os.environ.get('DATABASE_USER', None)
DATABASE_PASSWORD = os.environ.get('DATABASE_PASSWORD', None)
MYPROJECT_MISSION_NAME = os.environ.get('MYPROJECT_MISSION_NAME', None)
MYPROJECT_DELAY_SECONDS = os.environ.get('MYPROJECT_DELAY_SECONDS', 0)
MYPROJECT_MISSION_START = os.environ.get('MYPROJECT_MISSION_START', '2000-01-01T00:00:00Z')
MYPROJECT_MISSION_END = os.environ.get('MYPROJECT_MISSION_END', '2000-02-01T00:00:00Z')
MYPROJECT_TIME_ZONE = os.environ.get('MYPROJECT_TIME_ZONE', 'myproject.time.MissionElapsedTime')
MYPROJECT_SCHEDULE_URL = os.environ.get('MYPROJECT_SCHEDULE_URL', None)
AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME', 'myproject')
AWS_S3_BUCKET_NAME_STATIC = os.environ.get('AWS_S3_BUCKET_NAME_STATIC', 'myproject')
AWS_S3_HOST = os.environ.get('AWS_S3_HOST', None)
AWS_S3_ACCESS_KEY_ID = os.environ.get('AWS_S3_ACCESS_KEY_ID', None)
AWS_S3_SECRET_ACCESS_KEY = os.environ.get('AWS_S3_SECRET_ACCESS_KEY', None)
GOOGLE_ANALYTICS_CODE = os.environ.get('GOOGLE_ANALYTICS_CODE', None)
except KeyError as e:
raise ImproperlyConfigured(f'You must set {e} environment variable. Please refer to the myproject documentation.')
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
ROOT_URLCONF = 'myproject.urls'
WSGI_APPLICATION = 'myproject.wsgi.application'
ALLOWED_HOSTS = [ALLOWED_HOST, '192.168.8.2', '192.168.8.3']
INSTALLED_APPS = [
'rest_framework',
'rest_framework_swagger',
'storages',
'emoji_picker',
# 'rosetta',
'myproject._common',
'myproject.menu.MenuConfig',
'myproject.authorization.apps.AuthorizationConfig',
'myproject.feedback.apps.FeedbackConfig',
'myproject.system.apps.SystemConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myproject.biolab.apps.BiolabConfig',
'myproject.building.apps.BuildingConfig',
'myproject.communication.apps.CommunicationConfig',
'myproject.extravehicular.apps.ExtravehicularConfig',
'myproject.food.apps.FoodConfig',
'myproject.health.apps.HealthConfig',
'myproject.workout.apps.WorkoutConfig',
'myproject.inventory.apps.InventoryConfig',
'myproject.notification.apps.NotificationsConfig',
'myproject.reporting.apps.ReportingConfig',
'myproject.sensors.apps.SensorsConfig',
'myproject.time.apps.TimezoneConfig',
'myproject.water.apps.WaterConfig',
]
MIDDLEWARE = [
'django.middleware.cache.UpdateCacheMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware',
]
TEMPLATES = [{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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']}
}]
# https://docs.djangoproject.com/en/stable/ref/settings/#auth-password-validators
AUTH_USER_MODEL = 'authorization.User'
AUTH_PASSWORD_VALIDATORS = [
{'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator'},
{'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator'},
{'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator'},
{'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator'},
]
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.ModelBackend',
]
if SECURE_SSL_REDIRECT == 'True':
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_HSTS_SECONDS = 3600
else:
SECURE_SSL_REDIRECT = False
SESSION_COOKIE_SECURE = False
CSRF_COOKIE_SECURE = False
SECURE_HSTS_SECONDS = 0
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_BROWSER_XSS_FILTER = True
X_FRAME_OPTIONS = 'DENY'
# Internationalization
# https://docs.djangoproject.com/en/stable/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
en_formats.DATETIME_FORMAT = 'Y-m-d H:i'
en_formats.DATE_FORMAT = 'Y-m-d'
en_formats.TIME_FORMAT = 'H:i'
TIME_INPUT_FORMATS = ['%H:%M', '%H:%M:%S']
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'
}
}
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
],
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
],
}
SWAGGER_SETTINGS = {
'DOC_EXPANSION': 'list',
'OPERATIONS_SORTER': 'alpha',
'api_version': '1.0',
}
LOGGING = {}
MEGABYTE = 1_000_000
# Maximum size, in bytes, of a request before it will be streamed to the
# file system instead of into memory.
FILE_UPLOAD_MAX_MEMORY_SIZE = 100 * MEGABYTE
# Maximum size in bytes of request data (excluding file uploads) that will be
# read before a SuspiciousOperation (RequestDataTooBig) is raised.
DATA_UPLOAD_MAX_MEMORY_SIZE = 100 * MEGABYTE
MEDIA_LOCATION = 'media'
STATIC_LOCATION = 'static'
MYPROJECT = {
'MISSION_NAME': MYPROJECT_MISSION_NAME,
'DELAY': timedelta(seconds=int(MYPROJECT_DELAY_SECONDS)),
'MISSION_START': datetime.strptime(MYPROJECT_MISSION_START, '%Y-%m-%dT%H:%M:%SZ').replace(tzinfo=timezone.utc),
'MISSION_END': datetime.strptime(MYPROJECT_MISSION_END, '%Y-%m-%dT%H:%M:%SZ').replace(tzinfo=timezone.utc),
'TIME_ZONE': MYPROJECT_TIME_ZONE,
'SCHEDULE_URL': MYPROJECT_SCHEDULE_URL,
}
DEFAULT_AUTO_FIELD = 'django.db.models.AutoField'
DATABASES = {
'default': {
'ENGINE': DATABASE_ENGINE,
'NAME': DATABASE_NAME,
'USER': DATABASE_USER,
'PASSWORD': DATABASE_PASSWORD,
'HOST': DATABASE_HOST,
'PORT': int(DATABASE_PORT) if DATABASE_PORT else None,
}
}
if os.path.exists('/tmp/myproject/memcached.sock'):
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache',
'LOCATION': '/tmp/myproject/memcached.sock',
# Use binary memcache protocol (needed for authentication)
'BINARY': True,
# TIMEOUT is not the connection timeout! It's the default expiration
# timeout that should be applied to keys! Setting it to `None`
# disables expiration.
'TIMEOUT': None,
'OPTIONS': {
# Enable faster IO
'tcp_nodelay': True,
# Keep connection alive
'tcp_keepalive': True,
# Timeout settings
'connect_timeout': 2000, # ms
'send_timeout': 750 * 1000, # us
'receive_timeout': 750 * 1000, # us
'_poll_timeout': 2000, # ms
# Better failover
'ketama': True,
'remove_failed': 1,
'retry_timeout': 2,
'dead_timeout': 30,
}
}
}
else:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
}
}
AWS_S3_BUCKET_AUTH = False
AWS_S3_MAX_AGE_SECONDS = 60 * 60 * 24 * 365 # 1 year.
AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'}
AWS_DEFAULT_ACL = 'public-read'
AWS_QUERYSTRING_AUTH = False
if AWS_S3_SECRET_ACCESS_KEY:
DEFAULT_FILE_STORAGE = 'myproject.system.storage.MediaStorage'
STATICFILES_STORAGE = 'myproject.system.storage.StaticStorage'
else:
DEFAULT_FILE_STORAGE = 'django.core.files.storage.FileSystemStorage'
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'
if DEBUG_TOOLBAR == 'True':
DEBUG_TOOLBAR = True
INSTALLED_APPS.append('debug_toolbar')
MIDDLEWARE.append('debug_toolbar.middleware.DebugToolbarMiddleware')
INTERNAL_IPS = ['127.0.0.1']
else:
DEBUG_TOOLBAR = False
if DEBUG == 'True':
DEBUG = True
ALLOWED_HOSTS.append('127.0.0.1')
ALLOWED_HOSTS.append('localhost')
MIDDLEWARE += ['myproject._common.middleware.cache.DisableBrowserCache']
else:
DEBUG = False
3.1.3. Assignments
# FIXME: Write tests
# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`
# %% About
# - Name: Django Settings DEBUG
# - Difficulty: easy
# - Lines: 1
# - Minutes: 3
# %% English
# 0. Use `myproject.myproject`
# 1. Modify the file: `myproject/settings.py`
# 2. Set `DEBUG` as `bool` from the environment variable `DJANGO_DEBUG`
# 3. Set `DEBUG=False` if the environment variable is not defined
# 4. Run doctests - all must succeed
# %% Polish
# 0. Użyj `myproject.myproject`
# 1. Zmodyfikuj plik: `myproject/settings.py`
# 2. Ustaw `DEBUG` jako wartość `bool` ze zmiennej środowiskowej `DJANGO_DEBUG`
# 3. Ustaw `DEBUG=False` jeżeli zmienna środowiskowa jest niezdefiniowana
# 4. Uruchom doctesty - wszystkie muszą się powieść
# %% Hints
# - `os.getenv(..., default=...)` - get the environment variable
# - `bool(...)` - convert to boolean
# - default value is `False`
# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 10), \
'Python 3.10+ required'
"""
# FIXME: Write tests
# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`
# %% About
# - Name: Django Settings STATIC and MEDIA
# - Difficulty: easy
# - Lines: 4
# - Minutes: 3
# %% English
# 0. Use `myproject.shop`
# 1. Modify the file: `myproject/settings.py`
# 2. Set `STATIC_ROOT` to `BASE_DIR / 'static'`
# 3. Set `MEDIA_ROOT` to `BASE_DIR / 'media'`
# 4. Set `MEDIA_URL` to `media/`
# 5. Run doctests - all must succeed
# %% Polish
# 0. Użyj `myproject.shop`
# 1. Zmodyfikuj plik: `myproject/settings.py`
# 2. Ustaw `STATIC_ROOT` na `BASE_DIR / 'static'`
# 3. Ustaw `MEDIA_ROOT` na `BASE_DIR / 'media'`
# 4. Ustaw `MEDIA_URL` na `media/`
# 5. Uruchom doctesty - wszystkie muszą się powieść
# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 10), \
'Python 3.10+ required'
"""
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent