| 1 |
from django.conf import settings |
| 2 |
from django.contrib.staticfiles.handlers import StaticFilesHandler |
| 3 |
from django.core.management.commands.runserver import Command as RunserverCommand |
| 4 |
|
| 5 |
|
| 6 |
class Command(RunserverCommand): |
| 7 |
help = ( |
| 8 |
"Starts a lightweight web server for development and also serves static files." |
| 9 |
) |
| 10 |
|
| 11 |
def add_arguments(self, parser): |
| 12 |
super().add_arguments(parser) |
| 13 |
parser.add_argument( |
| 14 |
"--nostatic", |
| 15 |
action="store_false", |
| 16 |
dest="use_static_handler", |
| 17 |
help="Tells Django to NOT automatically serve static files at STATIC_URL.", |
| 18 |
) |
| 19 |
parser.add_argument( |
| 20 |
"--insecure", |
| 21 |
action="store_true", |
| 22 |
dest="insecure_serving", |
| 23 |
help="Allows serving static files even if DEBUG is False.", |
| 24 |
) |
| 25 |
|
| 26 |
def get_handler(self, *args, **options): |
| 27 |
""" |
| 28 |
Return the static files serving handler wrapping the default handler, |
| 29 |
if static files should be served. Otherwise return the default handler. |
| 30 |
""" |
| 31 |
handler = super().get_handler(*args, **options) |
| 32 |
use_static_handler = options["use_static_handler"] |
| 33 |
insecure_serving = options["insecure_serving"] |
| 34 |
if use_static_handler and (settings.DEBUG or insecure_serving): |
| 35 |
return StaticFilesHandler(handler) |
| 36 |
return handler |