runserver.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536
  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. class Command(RunserverCommand):
  5. help = (
  6. "Starts a lightweight web server for development and also serves static files."
  7. )
  8. def add_arguments(self, parser):
  9. super().add_arguments(parser)
  10. parser.add_argument(
  11. "--nostatic",
  12. action="store_false",
  13. dest="use_static_handler",
  14. help="Tells Django to NOT automatically serve static files at STATIC_URL.",
  15. )
  16. parser.add_argument(
  17. "--insecure",
  18. action="store_true",
  19. dest="insecure_serving",
  20. help="Allows serving static files even if DEBUG is False.",
  21. )
  22. def get_handler(self, *args, **options):
  23. """
  24. Return the static files serving handler wrapping the default handler,
  25. if static files should be served. Otherwise return the default handler.
  26. """
  27. handler = super().get_handler(*args, **options)
  28. use_static_handler = options["use_static_handler"]
  29. insecure_serving = options["insecure_serving"]
  30. if use_static_handler and (settings.DEBUG or insecure_serving):
  31. return StaticFilesHandler(handler)
  32. return handler