From 1c8ebcad218e02b2cea797af15ddc9791d22ab01 Mon Sep 17 00:00:00 2001 From: SKairinos Date: Mon, 18 Sep 2023 15:08:39 +0100 Subject: [PATCH] fix: add urls helper --- codeforlife/settings/custom.py | 1 - codeforlife/urls.py | 57 ++++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 1 deletion(-) create mode 100644 codeforlife/urls.py diff --git a/codeforlife/settings/custom.py b/codeforlife/settings/custom.py index cea6ca3..d3bd0e9 100644 --- a/codeforlife/settings/custom.py +++ b/codeforlife/settings/custom.py @@ -18,7 +18,6 @@ # The base url of the current service. # The root service does not need its name included in the base url. SERVICE_BASE_URL = f"{SERVICE_PROTOCOL}://{SERVICE_DOMAIN}:{SERVICE_PORT}" -SERVICE_BASE_ROUTE = "" if SERVICE_IS_ROOT else f"{SERVICE_NAME}/" if not SERVICE_IS_ROOT: SERVICE_BASE_URL += f"/{SERVICE_NAME}" diff --git a/codeforlife/urls.py b/codeforlife/urls.py new file mode 100644 index 0000000..727d203 --- /dev/null +++ b/codeforlife/urls.py @@ -0,0 +1,57 @@ +from django.contrib import admin +from django.http import HttpResponse +from django.shortcuts import render +from django.urls import include, path, re_path +from rest_framework import status + +from .settings import SERVICE_IS_ROOT, SERVICE_NAME + + +def service_urlpatterns( + api_urls_path: str = "api.urls", + frontend_template_name: str = "frontend.html", +): + urlpatterns = [ + path( + "admin/", + admin.site.urls, + name="admin", + ), + path( + "api/", + include(api_urls_path), + name="api", + ), + re_path( + r"^api/.*", + lambda request: HttpResponse( + "API endpoint not found", + status=status.HTTP_404_NOT_FOUND, + ), + name="api-endpoint-not-found", + ), + re_path( + r".*", + lambda request: render(request, frontend_template_name), + name="frontend", + ), + ] + + if SERVICE_IS_ROOT: + return urlpatterns + + return [ + path( + f"{SERVICE_NAME}/", + include(urlpatterns), + name="service", + ), + re_path( + r".*", + lambda request: HttpResponse( + f'The base route is "{SERVICE_NAME}/".', + status=status.HTTP_404_NOT_FOUND, + ), + name="service-not-found", + ), + ]