From a4a275d0fdfef229586985084dc482b3d84ce95f Mon Sep 17 00:00:00 2001 From: Luis Alvergue Date: Mon, 9 Dec 2024 22:58:04 +0000 Subject: [PATCH] feat: implement /healthcheck endpoint implements the healthcheck as a middleware before the HOST_HEADER verification (in django.middleware.common.CommonMiddleware), so healthcheck requests always pass based on https://stackoverflow.com/a/64623669 --- pems/core/__init__.py | 0 pems/core/middleware.py | 19 +++++++++++++++++++ pems/settings.py | 1 + tests/pytest/core/__init__.py | 0 .../core/test_middleware_healthcheck.py | 6 ++++++ 5 files changed, 26 insertions(+) create mode 100644 pems/core/__init__.py create mode 100644 pems/core/middleware.py create mode 100644 tests/pytest/core/__init__.py create mode 100644 tests/pytest/core/test_middleware_healthcheck.py diff --git a/pems/core/__init__.py b/pems/core/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/pems/core/middleware.py b/pems/core/middleware.py new file mode 100644 index 0000000..284c2ee --- /dev/null +++ b/pems/core/middleware.py @@ -0,0 +1,19 @@ +""" +The core application: middleware definitions for request/response cycle. +""" + +from django.http import HttpResponse + +HEALTHCHECK_PATH = "/healthcheck" + + +class Healthcheck: + """Middleware intercepts and accepts /healthcheck requests.""" + + def __init__(self, get_response): + self.get_response = get_response + + def __call__(self, request): + if request.path == HEALTHCHECK_PATH: + return HttpResponse("Healthy", content_type="text/plain") + return self.get_response(request) diff --git a/pems/settings.py b/pems/settings.py index d034edf..d834a1f 100644 --- a/pems/settings.py +++ b/pems/settings.py @@ -36,6 +36,7 @@ def _filter_empty(ls): MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", + "pems.core.middleware.Healthcheck", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", diff --git a/tests/pytest/core/__init__.py b/tests/pytest/core/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/pytest/core/test_middleware_healthcheck.py b/tests/pytest/core/test_middleware_healthcheck.py new file mode 100644 index 0000000..1519fa0 --- /dev/null +++ b/tests/pytest/core/test_middleware_healthcheck.py @@ -0,0 +1,6 @@ +from pems.core.middleware import HEALTHCHECK_PATH + + +def test_healthcheck(client): + response = client.get(HEALTHCHECK_PATH) + assert response.status_code == 200