github.com/ddev/ddev@v1.23.2-0.20240519125000-d824ffe36ff3/containers/ddev-webserver/ddev-webserver-base-files/usr/local/bin/find-django-settings-file.py (about)

     1  #!/usr/bin/env python
     2  """
     3  Find out what directory might have settings file, based
     4  on DJANGO_SETTINGS_MODULE or just finding a settings.py
     5  """
     6  import os
     7  import sys
     8  import importlib
     9  import inspect
    10  from pathlib import Path
    11  
    12  # Function to search for the settings.py file
    13  def find_settings_file(path: Path):
    14      for root, dirs, files in os.walk(path):
    15          if "settings.py" in files:
    16              return Path(root) / "settings.py"
    17      return None
    18  
    19  def convert_import_path(import_path):
    20      parts = import_path.split(".")
    21      gunicorn_path = ".".join(parts[:-1]) + ":" + parts[-1]
    22      return gunicorn_path
    23  
    24  def get_settings_filename():
    25      django_settings_module = os.environ.get('DJANGO_SETTINGS_MODULE')
    26      settings_file = ""
    27      if django_settings_module:
    28          try:
    29              # Import the settings module
    30              module = importlib.import_module(django_settings_module)
    31  
    32              # Get the file path of the imported module
    33              settings_file = inspect.getfile(module)
    34  
    35              return settings_file
    36          except ImportError:
    37              print(f"Could not import the specified DJANGO_SETTINGS_MODULE: {django_settings_module}")
    38              return None
    39      else:
    40          settings_file = find_settings_file(current_dir)
    41  
    42          # If settings.py is found, set the DJANGO_SETTINGS_MODULE environment variable
    43          if settings_file:
    44              sys.path.insert(0, str(settings_file.parent.parent))
    45          else:
    46              raise FileNotFoundError("Could not find the settings.py file.")
    47  
    48      return settings_file
    49  
    50  
    51  # Make sure that current dir is in module path
    52  current_dir = os.getcwd()
    53  if str(current_dir) not in sys.path:
    54      # Add the current directory to sys.path
    55      sys.path.insert(0, str(current_dir))
    56  
    57  # Check if DJANGO_SETTINGS_MODULE is set
    58  f = get_settings_filename()
    59  print(f"{f}")