From ae4f2646a8466f641f2888c97609bbd79283eb39 Mon Sep 17 00:00:00 2001 From: Bastien Abadie <abadie@teklia.com> Date: Thu, 24 Oct 2024 12:53:35 +0000 Subject: [PATCH] Support optional WSGI init method --- .../documents/management/commands/gunicorn.py | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/arkindex/documents/management/commands/gunicorn.py b/arkindex/documents/management/commands/gunicorn.py index bbf44a441d..fa87a8d3e4 100644 --- a/arkindex/documents/management/commands/gunicorn.py +++ b/arkindex/documents/management/commands/gunicorn.py @@ -3,8 +3,30 @@ import os import sys from django.conf import settings +from django.core.exceptions import ImproperlyConfigured from django.core.management.base import BaseCommand, CommandError from django.core.servers.basehttp import get_internal_wsgi_application +from django.utils.module_loading import import_string + + +def get_internal_wsgi_init(): + """ + Load an optional method to run during the WSGI initialisation + so it runs on the master process and not on the workers + Similar to get_internal_wsgi_application from django.core.servers.basehttp + """ + init_path = getattr(settings, "WSGI_INIT", None) + if init_path is None: + return + + try: + return import_string(init_path) + except ImportError as err: + raise ImproperlyConfigured( + f"WSGI init {init_path} could not be loaded; " + "Error importing module." + ) from err + class Command(BaseCommand): @@ -55,6 +77,11 @@ class Command(BaseCommand): class ArkindexServer(Application): """Run the Django WSGI app through gunicorn""" def init(self, *args, **kwargs): + + # Call optional init method + if init_method := get_internal_wsgi_init(): + init_method() + return { "bind": bind, "workers": workers, -- GitLab