Turn off caching of static files in Django development server

后端 未结 9 2226
灰色年华
灰色年华 2020-11-30 04:52

Is there an easy way to turn off caching of static files in Django\'s development server?

I\'m starting the server with the standard command:

<
9条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-30 05:05

    Django's contrib.staticfiles app automatically serves staticfiles for you by overriding the runserver command. With this configuration you can't control the way it serves the static files.

    You can prevent the staticfiles app from serving the static files by adding the --nostatic option to the runserver command:

    ./manage.py runserver --nostatic
    

    Then you can write an url config to manually serve the static files with headers that prevent the browser from caching the response:

    from django.conf import settings
    from django.contrib.staticfiles.views import serve as serve_static
    from django.views.decorators.cache import never_cache
    
    urlpatterns = patterns('', )
    
    if settings.DEBUG:
        urlpatterns += patterns('',
            url(r'^static/(?P.*)$', never_cache(serve_static)),
        )
    

    If you want your manage.py runserver command to have the --nostatic option on by default, you can put this in your manage.py:

    if '--nostatic' not in sys.argv:
        sys.argv.append('--nostatic')
    

提交回复
热议问题