Debian Codegraph @

django/core/management/commands/shell.py

raw
1 import os
2 import select
3 import sys
4 import traceback
5 from collections import defaultdict
6 from importlib import import_module
7
8 from django.apps import apps
9 from django.core.exceptions import AppRegistryNotReady
10 from django.core.management import BaseCommand, CommandError
11 from django.utils.datastructures import OrderedSet
12 from django.utils.module_loading import import_string as import_dotted_path
13
14
15 class Command(BaseCommand):
16 help = (
17 "Runs a Python interactive interpreter. Tries to use IPython or "
18 "bpython, if one of them is available. Any standard input is executed "
19 "as code."
20 )
21
22 requires_system_checks = []
23 shells = ["ipython", "bpython", "python"]
24
25 def add_arguments(self, parser):
26 parser.add_argument(
27 "--no-startup",
28 action="store_true",
29 help=(
30 "When using plain Python, ignore the PYTHONSTARTUP environment "
31 "variable and ~/.pythonrc.py script."
32 ),
33 )
34 parser.add_argument(
35 "--no-imports",
36 action="store_true",
37 help="Disable automatic imports of models.",
38 )
39 parser.add_argument(
40 "-i",
41 "--interface",
42 choices=self.shells,
43 help=(
44 "Specify an interactive interpreter interface. Available options: "
45 '"ipython", "bpython", and "python"'
46 ),
47 )
48 parser.add_argument(
49 "-c",
50 "--command",
51 help=(
52 "Instead of opening an interactive shell, run a command as Django and "
53 "exit."
54 ),
55 )
56
57 def ipython(self, options):
58 from IPython import start_ipython
59
60 start_ipython(argv=[], user_ns=self.get_namespace(**options))
61
62 def bpython(self, options):
63 import bpython
64
65 bpython.embed(self.get_namespace(**options))
66
67 def python(self, options):
68 import code
69
70 # Set up a dictionary to serve as the environment for the shell.
71 imported_objects = self.get_namespace(**options)
72
73 # We want to honor both $PYTHONSTARTUP and .pythonrc.py, so follow system
74 # conventions and get $PYTHONSTARTUP first then .pythonrc.py.
75 if not options["no_startup"]:
76 for pythonrc in OrderedSet(
77 [os.environ.get("PYTHONSTARTUP"), os.path.expanduser("~/.pythonrc.py")]
78 ):
79 if not pythonrc:
80 continue
81 if not os.path.isfile(pythonrc):
82 continue
83 with open(pythonrc) as handle:
84 pythonrc_code = handle.read()
85 # Match the behavior of the cpython shell where an error in
86 # PYTHONSTARTUP prints an exception and continues.
87 try:
88 exec(compile(pythonrc_code, pythonrc, "exec"), imported_objects)
89 except Exception:
90 traceback.print_exc()
91
92 # By default, this will set up readline to do tab completion and to read and
93 # write history to the .python_history file, but this can be overridden by
94 # $PYTHONSTARTUP or ~/.pythonrc.py.
95 try:
96 hook = sys.__interactivehook__
97 except AttributeError:
98 # Match the behavior of the cpython shell where a missing
99 # sys.__interactivehook__ is ignored.
100 pass
101 else:
102 try:
103 hook()
104 except Exception:
105 # Match the behavior of the cpython shell where an error in
106 # sys.__interactivehook__ prints a warning and the exception
107 # and continues.
108 print("Failed calling sys.__interactivehook__")
109 traceback.print_exc()
110
111 # Set up tab completion for objects imported by $PYTHONSTARTUP or
112 # ~/.pythonrc.py.
113 try:
114 import readline
115 import rlcompleter
116
117 readline.set_completer(rlcompleter.Completer(imported_objects).complete)
118 except ImportError:
119 pass
120
121 # Start the interactive interpreter.
122 code.interact(local=imported_objects)
123
124 def get_auto_imports(self):
125 """Return a sequence of import paths for objects to be auto-imported.
126
127 By default, import paths for models in INSTALLED_APPS are included,
128 with models from earlier apps taking precedence in case of a name
129 collision.
130
131 For example, for an unchanged INSTALLED_APPS, this method returns:
132
133 [
134 "django.contrib.sessions.models.Session",
135 "django.contrib.contenttypes.models.ContentType",
136 "django.contrib.auth.models.User",
137 "django.contrib.auth.models.Group",
138 "django.contrib.auth.models.Permission",
139 "django.contrib.admin.models.LogEntry",
140 ]
141
142 """
143 app_models_imports = [
144 f"{model.__module__}.{model.__name__}"
145 for model in reversed(apps.get_models())
146 if model.__module__
147 ]
148 return app_models_imports
149
150 def get_namespace(self, **options):
151 if options and options.get("no_imports"):
152 return {}
153
154 verbosity = options["verbosity"] if options else 0
155
156 try:
157 apps.check_models_ready()
158 except AppRegistryNotReady:
159 if verbosity > 0:
160 settings_env_var = os.getenv("DJANGO_SETTINGS_MODULE")
161 self.stdout.write(
162 "Automatic imports are disabled since settings are not configured."
163 f"\nDJANGO_SETTINGS_MODULE value is {settings_env_var!r}.\n"
164 "HINT: Ensure that the settings module is configured and set.",
165 self.style.ERROR,
166 ending="\n\n",
167 )
168 return {}
169
170 path_imports = self.get_auto_imports()
171 if path_imports is None:
172 return {}
173
174 auto_imports = defaultdict(list)
175 import_errors = []
176 for path in path_imports:
177 try:
178 obj = import_dotted_path(path) if "." in path else import_module(path)
179 except ImportError:
180 import_errors.append(path)
181 continue
182
183 if "." in path:
184 module, name = path.rsplit(".", 1)
185 else:
186 module = None
187 name = path
188 if (name, obj) not in auto_imports[module]:
189 auto_imports[module].append((name, obj))
190
191 namespace = {
192 name: obj for items in auto_imports.values() for name, obj in items
193 }
194
195 if verbosity < 1:
196 return namespace
197
198 errors = len(import_errors)
199 if errors:
200 msg = "\n".join(f" {e}" for e in import_errors)
201 objects = "objects" if errors != 1 else "object"
202 self.stdout.write(
203 f"{errors} {objects} could not be automatically imported:\n\n{msg}",
204 self.style.ERROR,
205 ending="\n\n",
206 )
207
208 amount = len(namespace)
209 objects_str = "objects" if amount != 1 else "object"
210 msg = f"{amount} {objects_str} imported automatically"
211
212 if verbosity < 2:
213 if amount:
214 msg += " (use -v 2 for details)"
215 self.stdout.write(f"{msg}.", self.style.SUCCESS, ending="\n\n")
216 return namespace
217
218 top_level = auto_imports.pop(None, [])
219 import_string = "\n".join(
220 [f" import {obj}" for obj, _ in top_level]
221 + [
222 f" from {module} import {objects}"
223 for module, imported_objects in auto_imports.items()
224 if (objects := ", ".join(i[0] for i in imported_objects))
225 ]
226 )
227
228 try:
229 import isort
230 except ImportError:
231 pass
232 else:
233 import_string = isort.code(import_string)
234
235 if import_string:
236 msg = f"{msg}:\n\n{import_string}"
237 else:
238 msg = f"{msg}."
239
240 self.stdout.write(msg, self.style.SUCCESS, ending="\n\n")
241
242 return namespace
243
244 def handle(self, **options):
245 # Execute the command and exit.
246 if options["command"]:
247 exec(options["command"], {**globals(), **self.get_namespace(**options)})
248 return
249
250 # Execute stdin if it has anything to read and exit.
251 # Not supported on Windows due to select.select() limitations.
252 if (
253 sys.platform != "win32"
254 and not sys.stdin.isatty()
255 and select.select([sys.stdin], [], [], 0)[0]
256 ):
257 exec(sys.stdin.read(), {**globals(), **self.get_namespace(**options)})
258 return
259
260 available_shells = (
261 [options["interface"]] if options["interface"] else self.shells
262 )
263
264 for shell in available_shells:
265 try:
266 return getattr(self, shell)(options)
267 except ImportError:
268 pass
269 raise CommandError("Couldn't import {} interface.".format(shell))