Created
February 10, 2012 18:45
-
-
Save jordanorelli/1791579 to your computer and use it in GitHub Desktop.
A static file view for Django
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks, btw, in django 2.x the parameter 'mimetype' is changed to 'content_type'