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

The django.contrib.staticfiles settings look fine, since all the static files are served as expected. However, for example. / static / * .css files do not get gzipped, although I have GZipMiddleware enabled.

Fyi. my html views really get gzipped, only the files served by the staticfiles application are not used. Doesn't these answers seem to go through the middleware chain?

+6
source share
3 answers

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

You can then use the url template to serve static files as follows:

 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 launched without --nostatic, django will automatically serve things in STATIC_URL without going through the middleware chain.

Thanks to Dave for his pointers!

+5
source

Is it possible that you do not have GZipMiddleware at the top of your settings.MIDDLEWARE_CLASSES ? This can cause strange behavior.

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

EDIT: If this is not the case, what if you serve the files β€œmanually” through 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 can just point it to your Django server (no gunicorn / uwsgi / whatever is needed).

+2
source

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

0
source

Source: https://habr.com/ru/post/898174/


All Articles