File size: 1,289 Bytes
b856986
 
 
 
9e798a1
 
b856986
9e798a1
 
b856986
9e798a1
 
b856986
 
9e798a1
 
 
 
 
b856986
9e798a1
b856986
 
 
9e798a1
b856986
9e798a1
 
 
 
01a1238
9e798a1
 
b856986
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import importlib
import os
from typing import List


def discover_models(target_file: str, directory: str = None) -> List[str]:
    """
    Discover and import target files (e.g., models.py) in all directories and subdirectories.

    :param target_file: The filename to look for in subdirectories (e.g., "models.py").
    :param directory: The root directory to start searching from.
                      Defaults to the directory where this script is located.
    :return: A list of module paths as strings.
    """
    if directory is None:
        directory = os.path.dirname(
            os.path.abspath(__file__)
        )  # Use current directory of the script

    model_modules = []

    # Traverse directory and subdirectories
    for root, _, files in os.walk(directory):
        if target_file in files:
            # Construct the module path relative to the given directory
            relative_path = os.path.relpath(root, directory)
            module_name = os.path.join(relative_path, target_file).replace(
                os.sep, "."
            )  # Correct dot notation
            module_name = module_name[:-3]  # Remove '.py' extension
            model_modules.append("App." + module_name)

    print("Discovered models:", model_modules)
    return model_modules