github.com/ddev/ddev@v1.23.2-0.20240519125000-d824ffe36ff3/containers/ddev-webserver/ddev-webserver-base-files/usr/local/bin/start-gunicorn.py (about) 1 #!/usr/bin/env python 2 """ 3 Start up gunicorn, with 4 1. WSGI_APP environment variable setting if it exists 5 2. WSGI_APP derived from django settings if it exists 6 3. Fail but run a placeholder sleep infinity 7 """ 8 import os 9 import sys 10 import subprocess 11 from pathlib import Path 12 13 bind_address = "0.0.0.0:8000" 14 15 def convert_import_path(import_path): 16 parts = import_path.split(".") 17 gunicorn_path = ".".join(parts[:-1]) + ":" + parts[-1] 18 return gunicorn_path 19 20 def convert_settings_path(settings_file_path, project_root): 21 if project_root not in sys.path: 22 sys.path.append(project_root) 23 24 relative_path = os.path.relpath(settings_file_path, project_root) 25 26 module_path = os.path.splitext(relative_path)[0] 27 28 module_path = module_path.replace(os.path.sep, '.') 29 30 return module_path 31 32 def launch_gunicorn(wsgi_application, bind_address): 33 command = f"gunicorn -b {bind_address} -w 4 --reload --log-level debug --log-file - {wsgi_application}" 34 print(command) 35 process = subprocess.Popen(command, shell=True) 36 return process 37 38 39 # Make sure that current dir is in module path 40 current_dir = os.getcwd() 41 if str(current_dir) not in sys.path: 42 # Add the current directory to sys.path 43 sys.path.insert(0, str(current_dir)) 44 45 print(f"sys.path={sys.path}") 46 47 wsgi_app = os.getenv("WSGI_APP") 48 django_settings_module = os.getenv("DJANGO_SETTINGS_MODULE") 49 ddev_project_type = os.getenv("DDEV_PROJECT_TYPE") 50 print(f"WSGI_APP environment variable={wsgi_app} DJANGO_SETTINGS_MODULE={django_settings_module}") 51 52 53 if wsgi_app: 54 process = launch_gunicorn(wsgi_app, bind_address) 55 print(f"Launched Gunicorn for {wsgi_app} at {bind_address}") 56 57 elif ddev_project_type == "django4": 58 rv = subprocess.run(['python', '/usr/local/bin/find-django-settings-file.py'], stdout=subprocess.PIPE, text=True) 59 settings_file = rv.stdout 60 print(f"settings_file='{settings_file}'") 61 django_settings_module = convert_settings_path(settings_file, "/var/www/html") 62 print(f"django_settings_module='{django_settings_module}'") 63 os.environ["DJANGO_SETTINGS_MODULE"] = django_settings_module 64 from django.conf import settings 65 wsgi_application = settings.WSGI_APPLICATION 66 print(f"wsgi_application from django='{wsgi_application}'") 67 if wsgi_application: 68 wsgi_app = convert_import_path(wsgi_application) 69 print(f"Launching Gunicorn for {wsgi_app} at {bind_address}") 70 process = launch_gunicorn(wsgi_app, bind_address) 71 else: 72 print("wsgi_application not found in the settings module, just running sleep infinity instead") 73 74 subprocess.run(['sleep', "infinity"]) 75