runserver.py 1.3 KB

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