Debian Codegraph @

django/core/management/commands/runserver.py

raw
1 import errno
2 import os
3 import re
4 import socket
5 import sys
6 from datetime import datetime
7
8 from django.conf import settings
9 from django.core.management.base import BaseCommand, CommandError
10 from django.core.servers.basehttp import WSGIServer, get_internal_wsgi_application, run
11 from django.db import connections
12 from django.utils import autoreload
13 from django.utils.regex_helper import _lazy_re_compile
14 from django.utils.version import get_docs_version
15
16 naiveip_re = _lazy_re_compile(
17 r"""^(?:
18 (?P<addr>
19 (?P<ipv4>\d{1,3}(?:\.\d{1,3}){3}) | # IPv4 address
20 (?P<ipv6>\[[a-fA-F0-9:]+\]) | # IPv6 address
21 (?P<fqdn>[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*) # FQDN
22 ):)?(?P<port>\d+)$""",
23 re.X,
24 )
25
26
27 class Command(BaseCommand):
28 help = "Starts a lightweight web server for development."
29
30 stealth_options = ("shutdown_message",)
31 suppressed_base_arguments = {"--verbosity", "--traceback"}
32
33 default_addr = "127.0.0.1"
34 default_addr_ipv6 = "::1"
35 default_port = "8000"
36 protocol = "http"
37 server_cls = WSGIServer
38
39 def add_arguments(self, parser):
40 parser.add_argument(
41 "addrport", nargs="?", help="Optional port number, or ipaddr:port"
42 )
43 parser.add_argument(
44 "--ipv6",
45 "-6",
46 action="store_true",
47 dest="use_ipv6",
48 help="Tells Django to use an IPv6 address.",
49 )
50 parser.add_argument(
51 "--nothreading",
52 action="store_false",
53 dest="use_threading",
54 help="Tells Django to NOT use threading.",
55 )
56 parser.add_argument(
57 "--noreload",
58 action="store_false",
59 dest="use_reloader",
60 help="Tells Django to NOT use the auto-reloader.",
61 )
62
63 def execute(self, *args, **options):
64 if options["no_color"]:
65 # We rely on the environment because it's currently the only
66 # way to reach WSGIRequestHandler. This seems an acceptable
67 # compromise considering `runserver` runs indefinitely.
68 os.environ["DJANGO_COLORS"] = "nocolor"
69 super().execute(*args, **options)
70
71 def get_handler(self, *args, **options):
72 """Return the default WSGI handler for the runner."""
73 return get_internal_wsgi_application()
74
75 def get_check_kwargs(self, options):
76 """Validation is called explicitly each time the server reloads."""
77 return {"tags": set()}
78
79 def handle(self, *args, **options):
80 if not settings.DEBUG and not settings.ALLOWED_HOSTS:
81 raise CommandError("You must set settings.ALLOWED_HOSTS if DEBUG is False.")
82
83 self.use_ipv6 = options["use_ipv6"]
84 if self.use_ipv6 and not socket.has_ipv6:
85 raise CommandError("Your Python does not support IPv6.")
86 self._raw_ipv6 = False
87 if not options["addrport"]:
88 self.addr = ""
89 self.port = self.default_port
90 else:
91 m = re.match(naiveip_re, options["addrport"])
92 if m is None:
93 raise CommandError(
94 '"%s" is not a valid port number '
95 "or address:port pair." % options["addrport"]
96 )
97 self.addr, _ipv4, _ipv6, _fqdn, self.port = m.groups()
98 if not self.port.isdigit():
99 raise CommandError("%r is not a valid port number." % self.port)
100 if self.addr:
101 if _ipv6:
102 self.addr = self.addr[1:-1]
103 self.use_ipv6 = True
104 self._raw_ipv6 = True
105 elif self.use_ipv6 and not _fqdn:
106 raise CommandError('"%s" is not a valid IPv6 address.' % self.addr)
107 if not self.addr:
108 self.addr = self.default_addr_ipv6 if self.use_ipv6 else self.default_addr
109 self._raw_ipv6 = self.use_ipv6
110 self.run(**options)
111
112 def run(self, **options):
113 """Run the server, using the autoreloader if needed."""
114 use_reloader = options["use_reloader"]
115
116 if use_reloader:
117 autoreload.run_with_reloader(self.inner_run, **options)
118 else:
119 self.inner_run(None, **options)
120
121 def inner_run(self, *args, **options):
122 # If an exception was silenced in ManagementUtility.execute in order
123 # to be raised in the child process, raise it now.
124 autoreload.raise_last_exception()
125
126 threading = options["use_threading"]
127 # 'shutdown_message' is a stealth option.
128 shutdown_message = options.get("shutdown_message", "")
129
130 if not options["skip_checks"]:
131 self.stdout.write("Performing system checks...\n\n")
132 check_kwargs = super().get_check_kwargs(options)
133 check_kwargs["display_num_errors"] = True
134 self.check(**check_kwargs)
135 # Need to check migrations here, so can't use the
136 # requires_migrations_check attribute.
137 self.check_migrations()
138 # Close all connections opened during migration checking.
139 for conn in connections.all(initialized_only=True):
140 conn.close()
141
142 try:
143 handler = self.get_handler(*args, **options)
144 run(
145 self.addr,
146 int(self.port),
147 handler,
148 ipv6=self.use_ipv6,
149 threading=threading,
150 on_bind=self.on_bind,
151 server_cls=self.server_cls,
152 )
153 except OSError as e:
154 # Use helpful error messages instead of ugly tracebacks.
155 ERRORS = {
156 errno.EACCES: "You don't have permission to access that port.",
157 errno.EADDRINUSE: "That port is already in use.",
158 errno.EADDRNOTAVAIL: "That IP address can't be assigned to.",
159 }
160 try:
161 error_text = ERRORS[e.errno]
162 except KeyError:
163 error_text = e
164 self.stderr.write("Error: %s" % error_text)
165 # Need to use an OS exit because sys.exit doesn't work in a thread
166 os._exit(1)
167 except KeyboardInterrupt:
168 if shutdown_message:
169 self.stdout.write(shutdown_message)
170 sys.exit(0)
171
172 def on_bind(self, server_port):
173 quit_command = "CTRL-BREAK" if sys.platform == "win32" else "CONTROL-C"
174
175 if self._raw_ipv6:
176 addr = f"[{self.addr}]"
177 elif self.addr == "0":
178 addr = "0.0.0.0"
179 else:
180 addr = self.addr
181
182 now = datetime.now().strftime("%B %d, %Y - %X")
183 version = self.get_version()
184 print(
185 f"{now}\n"
186 f"Django version {version}, using settings {settings.SETTINGS_MODULE!r}\n"
187 f"Starting development server at {self.protocol}://{addr}:{server_port}/\n"
188 f"Quit the server with {quit_command}.",
189 file=self.stdout,
190 )
191 docs_version = get_docs_version()
192 if os.environ.get("DJANGO_RUNSERVER_HIDE_WARNING") != "true":
193 self.stdout.write(
194 self.style.WARNING(
195 "WARNING: This is a development server. Do not use it in a "
196 "production setting. Use a production WSGI or ASGI server "
197 "instead.\nFor more information on production servers see: "
198 f"https://docs.djangoproject.com/en/{docs_version}/howto/"
199 "deployment/"
200 )
201 )