diff --git a/arkindex/documents/management/commands/gunicorn.py b/arkindex/documents/management/commands/gunicorn.py index bbf44a441d0b75a2049d1c5f30d84f2d52befc77..fa87a8d3e4fae88dcd6adb01520dc0bb42fda836 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,