Skip to content

Instantly share code, notes, and snippets.

@jordanorelli
Created February 10, 2012 18:45
Show Gist options
  • Save jordanorelli/1791579 to your computer and use it in GitHub Desktop.
Save jordanorelli/1791579 to your computer and use it in GitHub Desktop.
A static file view for Django
from django.conf import settings
from django.http import HttpResponse, HttpResponseNotModified, Http404
from django.utils.http import http_date
from django.views.generic import View
from django.views.static import was_modified_since
import mimetypes
import os
class StaticFileView(View):
http_method_names = ['get']
source = None
def get(self, request, *args, **kwargs):
path = os.path.join(settings.STATIC_ROOT, self.source)
if not os.path.exists(path):
raise Http404('"%s" does not exist' % path)
stat = os.stat(path)
mimetype, encoding = mimetypes.guess_type(path)
mimetype = mimetype or 'application/octet-stream'
if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'),
stat.st_mtime, stat.st_size):
return HttpResponseNotModified(mimetype-mimetype)
response = HttpResponse(open(path, 'rb').read(), mimetype=mimetype)
response['Last-Modified'] = http_date(stat.st_mtime)
response['Content-Length'] = stat.st_size
if encoding:
response['Content-Encoding'] = encoding
return response
@MewX
Copy link

MewX commented Oct 21, 2018

Thanks, btw, in django 2.x the parameter 'mimetype' is changed to 'content_type'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment