Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Settings improvements #107

Merged
merged 5 commits into from
Aug 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 47 additions & 18 deletions app/app/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = bool(os.getenv("DEBUG", ""))
DEBUG_TOOLBAR = DEBUG # to toggle separately if we want to

ALLOWED_HOSTS = os.getenv("ALLOWED_HOSTS", "").split()
USE_X_FORWARDED_HOST = bool(os.getenv("USE_X_FORWARDED_HOST", ""))
Expand All @@ -50,32 +51,35 @@
"accounts",
"django_filters",
]

# Add django-extensions to the installed apps if DEBUG is True
if DEBUG:
INSTALLED_APPS += [
"django_extensions",
"debug_toolbar",
]
if DEBUG_TOOLBAR:
INSTALLED_APPS += [
"debug_toolbar",
]

AUTH_USER_MODEL = "users.CustomUser"

MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"whitenoise.middleware.WhiteNoiseMiddleware",
# DebugToolbarMiddleware should go here if enabled. Done below. See
# https://django-debug-toolbar.readthedocs.io/en/latest/installation.html#add-the-middleware
"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",
"simple_history.middleware.HistoryRequestMiddleware",
"django.middleware.locale.LocaleMiddleware",
]

# Add debug toolbar middleware
if DEBUG:
MIDDLEWARE.insert(0, "debug_toolbar.middleware.DebugToolbarMiddleware")
if DEBUG and DEBUG_TOOLBAR:
MIDDLEWARE.insert(2, "debug_toolbar.middleware.DebugToolbarMiddleware")

ROOT_URLCONF = "app.urls"

Expand Down Expand Up @@ -116,16 +120,43 @@
}
}

# toolbar settings
if DEBUG:
DEBUG_TOOLBAR_CONFIG = {
"IS_RUNNING_TESTS": False,
"SHOW_TOOLBAR_CALLBACK": lambda request: DEBUG,
}
# Some things rely on the setting INTERNAL_IPS:
# - debug_toolbar.middleware.show_toolbar
# - django.template.context_processors.debug
# See https://docs.djangoproject.com/en/stable/ref/settings/#internal-ips
# Inside a docker container, it isn't trivial to get the IP address of the
# Docker host that will appear in REMOTE_ADDR. The following seems to work
# for now to add support for a range of IP addresses without having to put
# a huge list in INTERNAL_IPS, e.g. with
# map(str, ipaddress.ip_network('172.0.0.0/24'))
# If this can't resolve the name "host.docker.internal", we assume that the
# browser will contact localhost.
import socket

try:
host_ip = socket.gethostbyname("host.docker.internal")
except socket.gaierror:
# presumably not in docker
host_ip = None

import ipaddress

# Based on https://code.djangoproject.com/ticket/3237#comment:12
class CIDRList(list):
def __init__(self, addresses):
"""Create a new ip_network object for each address range provided."""
self.networks = [ipaddress.ip_network(address, strict=False) for address in addresses]

def __contains__(self, address):
"""Check if the given address is contained in any of the networks."""
return any([ipaddress.ip_address(address) in network for network in self.networks])

if host_ip:
INTERNAL_IPS = CIDRList([f"{host_ip}/8"])
else:
INTERNAL_IPS = ["127.0.0.1"]

INTERNAL_IPS = [
"host.docker.internal",
]

# Email settings
EMAIL_HOST = os.environ.get("EMAIL_HOST")
Expand Down Expand Up @@ -205,7 +236,7 @@

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

LOGGING_FOLDER_DEFAULT = os.path.abspath(os.path.join("/logging/"))
LOGGING_DIR = Path("/logging")

# Internationalization

Expand Down Expand Up @@ -252,9 +283,7 @@
"file": {
"level": os.environ.get("LOGGING_HANDLERS_LEVEL", "WARNING"),
"class": "logging.FileHandler",
"filename": os.path.join(
LOGGING_FOLDER_DEFAULT, os.environ.get("LOGGING_FILE", "debug.log")
),
"filename": LOGGING_DIR / os.environ.get("LOGGING_FILE", "debug.log"),
"formatter": "verbose",
},
},
Expand Down
3 changes: 2 additions & 1 deletion app/app/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,4 +49,5 @@

if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns.append(path("__debug__/", include("debug_toolbar.urls")))
if settings.DEBUG_TOOLBAR:
urlpatterns.append(path("__debug__/", include("debug_toolbar.urls")))
5 changes: 2 additions & 3 deletions app/general/tests/test_logging.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
import logging
import os
import sys

from django.test import TestCase


class LoggingTest(TestCase):
def setUp(self):
LOGGING_FOLDER_DEFAULT = os.path.abspath(os.path.join("/logging/"))
LOGGING_DIR = "/logging"
self.logger = logging.getLogger("django")
self.log_file = os.path.join(LOGGING_FOLDER_DEFAULT, "debug.log")
self.log_file = os.path.join(LOGGING_DIR, "debug.log")

def test_log_file_created(self):
"""Test if the log file is created."""
Expand Down
Loading