3.5. Settings Security

  • Modify myproject/settings.py

3.5.1. SECRET_KEY

>>> 
... from django.core.exceptions import ImproperlyConfigured
... from pathlib import Path
...
...
... SECRET_KEY_FILE = Path('../secret-key.txt')
...
... if not SECRET_KEY_FILE.exists():
...     raise ImproperlyConfigured('SECRET_KEY file does not exist')
...
... SECRET_KEY = SECRET_KEY_FILE.read_text().strip()
...
... if not SECRET_KEY:
...     raise ImproperlyConfigured('SECRET_KEY is empty')

3.5.2. HTTPS_ONLY

>>> 
... MYPROJECT_HTTPSONLY = bool(os.getenv('MYPROJECT_HTTPSONLY', default=False))
...
... if MYPROJECT_HTTPSONLY:
...     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'

3.5.3. Assignments

# FIXME: Write tests
# doctest: +SKIP_FILE
# %% 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 SECURITY_KEY
# - Difficulty: easy
# - Lines: 7
# - Minutes: 5

# %% English
# 0. Use `myproject.shop`
# 1. Modify the file: `myproject/settings.py`
# 2. Set `SECRET_KEY` as a content from file `../secret-key.txt`
# 3. If file not exist, or it is empty, rase `ImproperlyConfigured` exception
# 4. Run doctests - all must succeed

# %% Polish
# 0. Użyj `myproject.shop`
# 1. Zmodyfikuj plik: `myproject/settings.py`
# 2. Ustaw `SECRET_KEY` jako zawartość pliku `../secret-key.txt`
# 3. Jeżeli plik nie istnieje lub jest pusty, podnieś wyjątek `ImproperlyConfigured`
# 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'
"""