Django: How can I gzip staticfiles served in dev mode?

杀马特。学长 韩版系。学妹 提交于 2019-12-06 00:00:04

问题


My django.contrib.staticfiles settings seems to be ok as all static files get served as expected. However, eg. /static/*.css files do not get gzipped although I have GZipMiddleware turned on.

Fyi. my views html actually does get gzipped, only the files served by the staticfiles app dont. Seems these responses dont go through the middleware chain?


回答1:


The trick is to have the development server run with the '--nostatic' flag set: ./manage.py runserver --nostatic.

One then can user a url pattern for serving the static files like so:

if settings.DEBUG:
    static_pattern = r'^%s(?P<path>.*)$' % (settings.STATIC_URL[1:],)
    urlpatterns += patterns('django.contrib.staticfiles.views',
        url(static_pattern, 'serve', {'show_indexes': True}),
    )

When run without --nostatic, django will automatically serve things under STATIC_URL without going through the middleware chain.

Thanks to Dave for his pointers!




回答2:


Is it possible you don't have the GZipMiddleware AT THE TOP of your settings.MIDDLEWARE_CLASSES? That might cause weird behavior.

If this is a production server, though, you probably shouldn't be serving static files with django at all. I'd recommend gunicorn and nginx.

EDIT: If not that, what if you serve the files "manually" via urls.py, using something like:

urlpatterns += staticfiles_urlpatterns() + \
        patterns('',
            (r'^%s/(?P<path>.*)$' % settings.MEDIA_URL.strip('/'), 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
            *[(r'^%s/(?P<path>.*)$' % settings.STATIC_URL.strip('/'), 'django.views.static.serve', {'document_root': path, 'show_indexes': True}) for path in settings.STATICFILES_DIRS]
        )

Alternative #3: Nginx is pretty easy to install locally, and you could just point it at your Django server (no need for gunicorn/uwsgi/whatever).




回答3:


In production environment your webserver (Apache/Nginx/IIS) takes care of gzipping static, so doesn't matter whether gzip works in dev or not.



来源:https://stackoverflow.com/questions/7576449/django-how-can-i-gzip-staticfiles-served-in-dev-mode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!