We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Django not available on startup
@matmair bad news. This has broken *stuff*..

https://github.com/inventree/InvenTree/runs/7837878419?check_suite_focus=true

Basically, the `invoke` script makes use of this file and must run *before* django is installed. Classic chicken and egg.

I think we might have to revert this one? LMK if you can see a cleaner solution otherwise I'll rewind this.

_Originally posted by @SchrodingersGat in https://github.com/inventree/InvenTree/issues/3536#issuecomment-1214999583_

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `InvenTree/InvenTree/config.py`
Content:
```
1 """Helper functions for loading InvenTree configuration options."""
2 
3 import logging
4 import os
5 import random
6 import shutil
7 import string
8 from pathlib import Path
9 
10 from django.contrib.staticfiles.storage import StaticFilesStorage
11 from django.core.files.storage import default_storage
12 
13 import yaml
14 
15 logger = logging.getLogger('inventree')
16 
17 
18 def is_true(x):
19     """Shortcut function to determine if a value "looks" like a boolean"""
20     return str(x).strip().lower() in ['1', 'y', 'yes', 't', 'true', 'on']
21 
22 
23 def get_base_dir() -> Path:
24     """Returns the base (top-level) InvenTree directory."""
25     return Path(__file__).parent.parent.resolve()
26 
27 
28 def get_config_file(create=True) -> Path:
29     """Returns the path of the InvenTree configuration file.
30 
31     Note: It will be created it if does not already exist!
32     """
33     base_dir = get_base_dir()
34 
35     cfg_filename = os.getenv('INVENTREE_CONFIG_FILE')
36 
37     if cfg_filename:
38         cfg_filename = Path(cfg_filename.strip()).resolve()
39     else:
40         # Config file is *not* specified - use the default
41         cfg_filename = base_dir.joinpath('config.yaml').resolve()
42 
43     if not cfg_filename.exists() and create:
44         print("InvenTree configuration file 'config.yaml' not found - creating default file")
45 
46         cfg_template = base_dir.joinpath("config_template.yaml")
47         shutil.copyfile(cfg_template, cfg_filename)
48         print(f"Created config file {cfg_filename}")
49 
50     return cfg_filename
51 
52 
53 def load_config_data() -> map:
54     """Load configuration data from the config file."""
55 
56     cfg_file = get_config_file()
57 
58     with open(cfg_file, 'r') as cfg:
59         data = yaml.safe_load(cfg)
60 
61     return data
62 
63 
64 def get_setting(env_var=None, config_key=None, default_value=None):
65     """Helper function for retrieving a configuration setting value.
66 
67     - First preference is to look for the environment variable
68     - Second preference is to look for the value of the settings file
69     - Third preference is the default value
70 
71     Arguments:
72         env_var: Name of the environment variable e.g. 'INVENTREE_STATIC_ROOT'
73         config_key: Key to lookup in the configuration file
74         default_value: Value to return if first two options are not provided
75 
76     """
77 
78     # First, try to load from the environment variables
79     if env_var is not None:
80         val = os.getenv(env_var, None)
81 
82         if val is not None:
83             return val
84 
85     # Next, try to load from configuration file
86     if config_key is not None:
87         cfg_data = load_config_data()
88 
89         result = None
90 
91         # Hack to allow 'path traversal' in configuration file
92         for key in config_key.strip().split('.'):
93 
94             if type(cfg_data) is not dict or key not in cfg_data:
95                 result = None
96                 break
97 
98             result = cfg_data[key]
99             cfg_data = cfg_data[key]
100 
101         if result is not None:
102             return result
103 
104     # Finally, return the default value
105     return default_value
106 
107 
108 def get_boolean_setting(env_var=None, config_key=None, default_value=False):
109     """Helper function for retreiving a boolean configuration setting"""
110 
111     return is_true(get_setting(env_var, config_key, default_value))
112 
113 
114 def get_media_dir(create=True):
115     """Return the absolute path for the 'media' directory (where uploaded files are stored)"""
116 
117     md = get_setting('INVENTREE_MEDIA_ROOT', 'media_root')
118 
119     if not md:
120         raise FileNotFoundError('INVENTREE_MEDIA_ROOT not specified')
121 
122     md = Path(md).resolve()
123 
124     if create:
125         md.mkdir(parents=True, exist_ok=True)
126 
127     return md
128 
129 
130 def get_static_dir(create=True):
131     """Return the absolute path for the 'static' directory (where static files are stored)"""
132 
133     sd = get_setting('INVENTREE_STATIC_ROOT', 'static_root')
134 
135     if not sd:
136         raise FileNotFoundError('INVENTREE_STATIC_ROOT not specified')
137 
138     sd = Path(sd).resolve()
139 
140     if create:
141         sd.mkdir(parents=True, exist_ok=True)
142 
143     return sd
144 
145 
146 def get_plugin_file():
147     """Returns the path of the InvenTree plugins specification file.
148 
149     Note: It will be created if it does not already exist!
150     """
151 
152     # Check if the plugin.txt file (specifying required plugins) is specified
153     plugin_file = get_setting('INVENTREE_PLUGIN_FILE', 'plugin_file')
154 
155     if not plugin_file:
156         # If not specified, look in the same directory as the configuration file
157         config_dir = get_config_file().parent
158         plugin_file = config_dir.joinpath('plugins.txt')
159     else:
160         # Make sure we are using a modern Path object
161         plugin_file = Path(plugin_file)
162 
163     if not plugin_file.exists():
164         logger.warning("Plugin configuration file does not exist - creating default file")
165         logger.info(f"Creating plugin file at '{plugin_file}'")
166 
167         # If opening the file fails (no write permission, for example), then this will throw an error
168         plugin_file.write_text("# InvenTree Plugins (uses PIP framework to install)\n\n")
169 
170     return plugin_file
171 
172 
173 def get_secret_key():
174     """Return the secret key value which will be used by django.
175 
176     Following options are tested, in descending order of preference:
177 
178     A) Check for environment variable INVENTREE_SECRET_KEY => Use raw key data
179     B) Check for environment variable INVENTREE_SECRET_KEY_FILE => Load key data from file
180     C) Look for default key file "secret_key.txt"
181     D) Create "secret_key.txt" if it does not exist
182     """
183 
184     # Look for environment variable
185     if secret_key := get_setting('INVENTREE_SECRET_KEY', 'secret_key'):
186         logger.info("SECRET_KEY loaded by INVENTREE_SECRET_KEY")  # pragma: no cover
187         return secret_key
188 
189     # Look for secret key file
190     if secret_key_file := get_setting('INVENTREE_SECRET_KEY_FILE', 'secret_key_file'):
191         secret_key_file = Path(secret_key_file).resolve()
192     else:
193         # Default location for secret key file
194         secret_key_file = get_base_dir().joinpath("secret_key.txt").resolve()
195 
196     if not secret_key_file.exists():
197         logger.info(f"Generating random key file at '{secret_key_file}'")
198 
199         # Create a random key file
200         options = string.digits + string.ascii_letters + string.punctuation
201         key = ''.join([random.choice(options) for i in range(100)])
202         secret_key_file.write_text(key)
203 
204     logger.info(f"Loading SECRET_KEY from '{secret_key_file}'")
205 
206     key_data = secret_key_file.read_text().strip()
207 
208     return key_data
209 
210 
211 def get_custom_file(env_ref: str, conf_ref: str, log_ref: str, lookup_media: bool = False):
212     """Returns the checked path to a custom file.
213 
214     Set lookup_media to True to also search in the media folder.
215     """
216     value = get_setting(env_ref, conf_ref, None)
217 
218     if not value:
219         return None
220 
221     static_storage = StaticFilesStorage()
222 
223     if static_storage.exists(value):
224         logger.info(f"Loading {log_ref} from static directory: {value}")
225     elif lookup_media and default_storage.exists(value):
226         logger.info(f"Loading {log_ref} from media directory: {value}")
227     else:
228         add_dir_str = ' or media' if lookup_media else ''
229         logger.warning(f"The {log_ref} file '{value}' could not be found in the static{add_dir_str} directories")
230         value = False
231 
232     return value
233
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/InvenTree/InvenTree/config.py b/InvenTree/InvenTree/config.py
--- a/InvenTree/InvenTree/config.py
+++ b/InvenTree/InvenTree/config.py
@@ -7,9 +7,6 @@
 import string
 from pathlib import Path
 
-from django.contrib.staticfiles.storage import StaticFilesStorage
-from django.core.files.storage import default_storage
-
 import yaml
 
 logger = logging.getLogger('inventree')
@@ -213,6 +210,9 @@
 
     Set lookup_media to True to also search in the media folder.
     """
+    from django.contrib.staticfiles.storage import StaticFilesStorage
+    from django.core.files.storage import default_storage
+
     value = get_setting(env_ref, conf_ref, None)
 
     if not value:

{"golden_diff": "diff --git a/InvenTree/InvenTree/config.py b/InvenTree/InvenTree/config.py\n--- a/InvenTree/InvenTree/config.py\n+++ b/InvenTree/InvenTree/config.py\n@@ -7,9 +7,6 @@\n import string\n from pathlib import Path\n \n-from django.contrib.staticfiles.storage import StaticFilesStorage\n-from django.core.files.storage import default_storage\n-\n import yaml\n \n logger = logging.getLogger('inventree')\n@@ -213,6 +210,9 @@\n \n     Set lookup_media to True to also search in the media folder.\n     \"\"\"\n+    from django.contrib.staticfiles.storage import StaticFilesStorage\n+    from django.core.files.storage import default_storage\n+\n     value = get_setting(env_ref, conf_ref, None)\n \n     if not value:\n", "issue": "Django not available on startup\n@matmair bad news. This has broken *stuff*..\r\n\r\nhttps://github.com/inventree/InvenTree/runs/7837878419?check_suite_focus=true\r\n\r\nBasically, the `invoke` script makes use of this file and must run *before* django is installed. Classic chicken and egg.\r\n\r\nI think we might have to revert this one? LMK if you can see a cleaner solution otherwise I'll rewind this.\r\n\r\n_Originally posted by @SchrodingersGat in https://github.com/inventree/InvenTree/issues/3536#issuecomment-1214999583_\n", "before_files": [{"content": "\"\"\"Helper functions for loading InvenTree configuration options.\"\"\"\n\nimport logging\nimport os\nimport random\nimport shutil\nimport string\nfrom pathlib import Path\n\nfrom django.contrib.staticfiles.storage import StaticFilesStorage\nfrom django.core.files.storage import default_storage\n\nimport yaml\n\nlogger = logging.getLogger('inventree')\n\n\ndef is_true(x):\n    \"\"\"Shortcut function to determine if a value \"looks\" like a boolean\"\"\"\n    return str(x).strip().lower() in ['1', 'y', 'yes', 't', 'true', 'on']\n\n\ndef get_base_dir() -> Path:\n    \"\"\"Returns the base (top-level) InvenTree directory.\"\"\"\n    return Path(__file__).parent.parent.resolve()\n\n\ndef get_config_file(create=True) -> Path:\n    \"\"\"Returns the path of the InvenTree configuration file.\n\n    Note: It will be created it if does not already exist!\n    \"\"\"\n    base_dir = get_base_dir()\n\n    cfg_filename = os.getenv('INVENTREE_CONFIG_FILE')\n\n    if cfg_filename:\n        cfg_filename = Path(cfg_filename.strip()).resolve()\n    else:\n        # Config file is *not* specified - use the default\n        cfg_filename = base_dir.joinpath('config.yaml').resolve()\n\n    if not cfg_filename.exists() and create:\n        print(\"InvenTree configuration file 'config.yaml' not found - creating default file\")\n\n        cfg_template = base_dir.joinpath(\"config_template.yaml\")\n        shutil.copyfile(cfg_template, cfg_filename)\n        print(f\"Created config file {cfg_filename}\")\n\n    return cfg_filename\n\n\ndef load_config_data() -> map:\n    \"\"\"Load configuration data from the config file.\"\"\"\n\n    cfg_file = get_config_file()\n\n    with open(cfg_file, 'r') as cfg:\n        data = yaml.safe_load(cfg)\n\n    return data\n\n\ndef get_setting(env_var=None, config_key=None, default_value=None):\n    \"\"\"Helper function for retrieving a configuration setting value.\n\n    - First preference is to look for the environment variable\n    - Second preference is to look for the value of the settings file\n    - Third preference is the default value\n\n    Arguments:\n        env_var: Name of the environment variable e.g. 'INVENTREE_STATIC_ROOT'\n        config_key: Key to lookup in the configuration file\n        default_value: Value to return if first two options are not provided\n\n    \"\"\"\n\n    # First, try to load from the environment variables\n    if env_var is not None:\n        val = os.getenv(env_var, None)\n\n        if val is not None:\n            return val\n\n    # Next, try to load from configuration file\n    if config_key is not None:\n        cfg_data = load_config_data()\n\n        result = None\n\n        # Hack to allow 'path traversal' in configuration file\n        for key in config_key.strip().split('.'):\n\n            if type(cfg_data) is not dict or key not in cfg_data:\n                result = None\n                break\n\n            result = cfg_data[key]\n            cfg_data = cfg_data[key]\n\n        if result is not None:\n            return result\n\n    # Finally, return the default value\n    return default_value\n\n\ndef get_boolean_setting(env_var=None, config_key=None, default_value=False):\n    \"\"\"Helper function for retreiving a boolean configuration setting\"\"\"\n\n    return is_true(get_setting(env_var, config_key, default_value))\n\n\ndef get_media_dir(create=True):\n    \"\"\"Return the absolute path for the 'media' directory (where uploaded files are stored)\"\"\"\n\n    md = get_setting('INVENTREE_MEDIA_ROOT', 'media_root')\n\n    if not md:\n        raise FileNotFoundError('INVENTREE_MEDIA_ROOT not specified')\n\n    md = Path(md).resolve()\n\n    if create:\n        md.mkdir(parents=True, exist_ok=True)\n\n    return md\n\n\ndef get_static_dir(create=True):\n    \"\"\"Return the absolute path for the 'static' directory (where static files are stored)\"\"\"\n\n    sd = get_setting('INVENTREE_STATIC_ROOT', 'static_root')\n\n    if not sd:\n        raise FileNotFoundError('INVENTREE_STATIC_ROOT not specified')\n\n    sd = Path(sd).resolve()\n\n    if create:\n        sd.mkdir(parents=True, exist_ok=True)\n\n    return sd\n\n\ndef get_plugin_file():\n    \"\"\"Returns the path of the InvenTree plugins specification file.\n\n    Note: It will be created if it does not already exist!\n    \"\"\"\n\n    # Check if the plugin.txt file (specifying required plugins) is specified\n    plugin_file = get_setting('INVENTREE_PLUGIN_FILE', 'plugin_file')\n\n    if not plugin_file:\n        # If not specified, look in the same directory as the configuration file\n        config_dir = get_config_file().parent\n        plugin_file = config_dir.joinpath('plugins.txt')\n    else:\n        # Make sure we are using a modern Path object\n        plugin_file = Path(plugin_file)\n\n    if not plugin_file.exists():\n        logger.warning(\"Plugin configuration file does not exist - creating default file\")\n        logger.info(f\"Creating plugin file at '{plugin_file}'\")\n\n        # If opening the file fails (no write permission, for example), then this will throw an error\n        plugin_file.write_text(\"# InvenTree Plugins (uses PIP framework to install)\\n\\n\")\n\n    return plugin_file\n\n\ndef get_secret_key():\n    \"\"\"Return the secret key value which will be used by django.\n\n    Following options are tested, in descending order of preference:\n\n    A) Check for environment variable INVENTREE_SECRET_KEY => Use raw key data\n    B) Check for environment variable INVENTREE_SECRET_KEY_FILE => Load key data from file\n    C) Look for default key file \"secret_key.txt\"\n    D) Create \"secret_key.txt\" if it does not exist\n    \"\"\"\n\n    # Look for environment variable\n    if secret_key := get_setting('INVENTREE_SECRET_KEY', 'secret_key'):\n        logger.info(\"SECRET_KEY loaded by INVENTREE_SECRET_KEY\")  # pragma: no cover\n        return secret_key\n\n    # Look for secret key file\n    if secret_key_file := get_setting('INVENTREE_SECRET_KEY_FILE', 'secret_key_file'):\n        secret_key_file = Path(secret_key_file).resolve()\n    else:\n        # Default location for secret key file\n        secret_key_file = get_base_dir().joinpath(\"secret_key.txt\").resolve()\n\n    if not secret_key_file.exists():\n        logger.info(f\"Generating random key file at '{secret_key_file}'\")\n\n        # Create a random key file\n        options = string.digits + string.ascii_letters + string.punctuation\n        key = ''.join([random.choice(options) for i in range(100)])\n        secret_key_file.write_text(key)\n\n    logger.info(f\"Loading SECRET_KEY from '{secret_key_file}'\")\n\n    key_data = secret_key_file.read_text().strip()\n\n    return key_data\n\n\ndef get_custom_file(env_ref: str, conf_ref: str, log_ref: str, lookup_media: bool = False):\n    \"\"\"Returns the checked path to a custom file.\n\n    Set lookup_media to True to also search in the media folder.\n    \"\"\"\n    value = get_setting(env_ref, conf_ref, None)\n\n    if not value:\n        return None\n\n    static_storage = StaticFilesStorage()\n\n    if static_storage.exists(value):\n        logger.info(f\"Loading {log_ref} from static directory: {value}\")\n    elif lookup_media and default_storage.exists(value):\n        logger.info(f\"Loading {log_ref} from media directory: {value}\")\n    else:\n        add_dir_str = ' or media' if lookup_media else ''\n        logger.warning(f\"The {log_ref} file '{value}' could not be found in the static{add_dir_str} directories\")\n        value = False\n\n    return value\n", "path": "InvenTree/InvenTree/config.py"}], "after_files": [{"content": "\"\"\"Helper functions for loading InvenTree configuration options.\"\"\"\n\nimport logging\nimport os\nimport random\nimport shutil\nimport string\nfrom pathlib import Path\n\nimport yaml\n\nlogger = logging.getLogger('inventree')\n\n\ndef is_true(x):\n    \"\"\"Shortcut function to determine if a value \"looks\" like a boolean\"\"\"\n    return str(x).strip().lower() in ['1', 'y', 'yes', 't', 'true', 'on']\n\n\ndef get_base_dir() -> Path:\n    \"\"\"Returns the base (top-level) InvenTree directory.\"\"\"\n    return Path(__file__).parent.parent.resolve()\n\n\ndef get_config_file(create=True) -> Path:\n    \"\"\"Returns the path of the InvenTree configuration file.\n\n    Note: It will be created it if does not already exist!\n    \"\"\"\n    base_dir = get_base_dir()\n\n    cfg_filename = os.getenv('INVENTREE_CONFIG_FILE')\n\n    if cfg_filename:\n        cfg_filename = Path(cfg_filename.strip()).resolve()\n    else:\n        # Config file is *not* specified - use the default\n        cfg_filename = base_dir.joinpath('config.yaml').resolve()\n\n    if not cfg_filename.exists() and create:\n        print(\"InvenTree configuration file 'config.yaml' not found - creating default file\")\n\n        cfg_template = base_dir.joinpath(\"config_template.yaml\")\n        shutil.copyfile(cfg_template, cfg_filename)\n        print(f\"Created config file {cfg_filename}\")\n\n    return cfg_filename\n\n\ndef load_config_data() -> map:\n    \"\"\"Load configuration data from the config file.\"\"\"\n\n    cfg_file = get_config_file()\n\n    with open(cfg_file, 'r') as cfg:\n        data = yaml.safe_load(cfg)\n\n    return data\n\n\ndef get_setting(env_var=None, config_key=None, default_value=None):\n    \"\"\"Helper function for retrieving a configuration setting value.\n\n    - First preference is to look for the environment variable\n    - Second preference is to look for the value of the settings file\n    - Third preference is the default value\n\n    Arguments:\n        env_var: Name of the environment variable e.g. 'INVENTREE_STATIC_ROOT'\n        config_key: Key to lookup in the configuration file\n        default_value: Value to return if first two options are not provided\n\n    \"\"\"\n\n    # First, try to load from the environment variables\n    if env_var is not None:\n        val = os.getenv(env_var, None)\n\n        if val is not None:\n            return val\n\n    # Next, try to load from configuration file\n    if config_key is not None:\n        cfg_data = load_config_data()\n\n        result = None\n\n        # Hack to allow 'path traversal' in configuration file\n        for key in config_key.strip().split('.'):\n\n            if type(cfg_data) is not dict or key not in cfg_data:\n                result = None\n                break\n\n            result = cfg_data[key]\n            cfg_data = cfg_data[key]\n\n        if result is not None:\n            return result\n\n    # Finally, return the default value\n    return default_value\n\n\ndef get_boolean_setting(env_var=None, config_key=None, default_value=False):\n    \"\"\"Helper function for retreiving a boolean configuration setting\"\"\"\n\n    return is_true(get_setting(env_var, config_key, default_value))\n\n\ndef get_media_dir(create=True):\n    \"\"\"Return the absolute path for the 'media' directory (where uploaded files are stored)\"\"\"\n\n    md = get_setting('INVENTREE_MEDIA_ROOT', 'media_root')\n\n    if not md:\n        raise FileNotFoundError('INVENTREE_MEDIA_ROOT not specified')\n\n    md = Path(md).resolve()\n\n    if create:\n        md.mkdir(parents=True, exist_ok=True)\n\n    return md\n\n\ndef get_static_dir(create=True):\n    \"\"\"Return the absolute path for the 'static' directory (where static files are stored)\"\"\"\n\n    sd = get_setting('INVENTREE_STATIC_ROOT', 'static_root')\n\n    if not sd:\n        raise FileNotFoundError('INVENTREE_STATIC_ROOT not specified')\n\n    sd = Path(sd).resolve()\n\n    if create:\n        sd.mkdir(parents=True, exist_ok=True)\n\n    return sd\n\n\ndef get_plugin_file():\n    \"\"\"Returns the path of the InvenTree plugins specification file.\n\n    Note: It will be created if it does not already exist!\n    \"\"\"\n\n    # Check if the plugin.txt file (specifying required plugins) is specified\n    plugin_file = get_setting('INVENTREE_PLUGIN_FILE', 'plugin_file')\n\n    if not plugin_file:\n        # If not specified, look in the same directory as the configuration file\n        config_dir = get_config_file().parent\n        plugin_file = config_dir.joinpath('plugins.txt')\n    else:\n        # Make sure we are using a modern Path object\n        plugin_file = Path(plugin_file)\n\n    if not plugin_file.exists():\n        logger.warning(\"Plugin configuration file does not exist - creating default file\")\n        logger.info(f\"Creating plugin file at '{plugin_file}'\")\n\n        # If opening the file fails (no write permission, for example), then this will throw an error\n        plugin_file.write_text(\"# InvenTree Plugins (uses PIP framework to install)\\n\\n\")\n\n    return plugin_file\n\n\ndef get_secret_key():\n    \"\"\"Return the secret key value which will be used by django.\n\n    Following options are tested, in descending order of preference:\n\n    A) Check for environment variable INVENTREE_SECRET_KEY => Use raw key data\n    B) Check for environment variable INVENTREE_SECRET_KEY_FILE => Load key data from file\n    C) Look for default key file \"secret_key.txt\"\n    D) Create \"secret_key.txt\" if it does not exist\n    \"\"\"\n\n    # Look for environment variable\n    if secret_key := get_setting('INVENTREE_SECRET_KEY', 'secret_key'):\n        logger.info(\"SECRET_KEY loaded by INVENTREE_SECRET_KEY\")  # pragma: no cover\n        return secret_key\n\n    # Look for secret key file\n    if secret_key_file := get_setting('INVENTREE_SECRET_KEY_FILE', 'secret_key_file'):\n        secret_key_file = Path(secret_key_file).resolve()\n    else:\n        # Default location for secret key file\n        secret_key_file = get_base_dir().joinpath(\"secret_key.txt\").resolve()\n\n    if not secret_key_file.exists():\n        logger.info(f\"Generating random key file at '{secret_key_file}'\")\n\n        # Create a random key file\n        options = string.digits + string.ascii_letters + string.punctuation\n        key = ''.join([random.choice(options) for i in range(100)])\n        secret_key_file.write_text(key)\n\n    logger.info(f\"Loading SECRET_KEY from '{secret_key_file}'\")\n\n    key_data = secret_key_file.read_text().strip()\n\n    return key_data\n\n\ndef get_custom_file(env_ref: str, conf_ref: str, log_ref: str, lookup_media: bool = False):\n    \"\"\"Returns the checked path to a custom file.\n\n    Set lookup_media to True to also search in the media folder.\n    \"\"\"\n    from django.contrib.staticfiles.storage import StaticFilesStorage\n    from django.core.files.storage import default_storage\n\n    value = get_setting(env_ref, conf_ref, None)\n\n    if not value:\n        return None\n\n    static_storage = StaticFilesStorage()\n\n    if static_storage.exists(value):\n        logger.info(f\"Loading {log_ref} from static directory: {value}\")\n    elif lookup_media and default_storage.exists(value):\n        logger.info(f\"Loading {log_ref} from media directory: {value}\")\n    else:\n        add_dir_str = ' or media' if lookup_media else ''\n        logger.warning(f\"The {log_ref} file '{value}' could not be found in the static{add_dir_str} directories\")\n        value = False\n\n    return value\n", "path": "InvenTree/InvenTree/config.py"}]}