diff options
| author | Jannis Leidel <jannis@leidel.info> | 2011-03-01 22:49:10 +0000 |
|---|---|---|
| committer | Jannis Leidel <jannis@leidel.info> | 2011-03-01 22:49:10 +0000 |
| commit | be4a2e3f3e0a04c87e6c9127cb1011df7c53e9e9 (patch) | |
| tree | 0eae17f8c273f3024c1df869a77865d5d612ad5f /django/views/static.py | |
| parent | 8f1987826311cca9e527ce34762ac035f799aa64 (diff) | |
Fixed #15281 -- Made the static view use an iterator when serving a file, effectively making this less of a memory hog. Also use the appropriate attributes of the stat object instead of indexes. Thanks for the initial patch, FunkyBob and aaugustin.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@15701 bcc190cf-cafb-0310-a4f2-bffc1f526a37
Diffstat (limited to 'django/views/static.py')
| -rw-r--r-- | django/views/static.py | 38 |
1 files changed, 32 insertions, 6 deletions
diff --git a/django/views/static.py b/django/views/static.py index 3aeb2ed98e..96acc859f1 100644 --- a/django/views/static.py +++ b/django/views/static.py @@ -7,14 +7,41 @@ import mimetypes import os import posixpath import re -import stat import urllib from django.template import loader from django.http import Http404, HttpResponse, HttpResponseRedirect, HttpResponseNotModified + from django.template import Template, Context, TemplateDoesNotExist from django.utils.http import http_date, parse_http_date + +class FileWrapper(object): + """ + Wrapper to convert file-like objects to iterables + """ + def __init__(self, filelike, blksize=8192): + self.filelike = filelike + self.blksize = blksize + if hasattr(filelike,'close'): + self.close = filelike.close + + def __getitem__(self,key): + data = self.filelike.read(self.blksize) + if data: + return data + raise IndexError + + def __iter__(self): + return self + + def next(self): + data = self.filelike.read(self.blksize) + if data: + return data + raise StopIteration + + def serve(request, path, document_root=None, show_indexes=False): """ Serve static files below a given point in the directory structure. @@ -56,12 +83,11 @@ def serve(request, path, document_root=None, show_indexes=False): mimetype, encoding = mimetypes.guess_type(fullpath) mimetype = mimetype or 'application/octet-stream' if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'), - statobj[stat.ST_MTIME], statobj[stat.ST_SIZE]): + statobj.st_mtime, statobj.st_size): return HttpResponseNotModified(mimetype=mimetype) - contents = open(fullpath, 'rb').read() - response = HttpResponse(contents, mimetype=mimetype) - response["Last-Modified"] = http_date(statobj[stat.ST_MTIME]) - response["Content-Length"] = len(contents) + response = HttpResponse(FileWrapper(open(fullpath, 'rb')), mimetype=mimetype) + response["Last-Modified"] = http_date(statobj.st_mtime) + response["Content-Length"] = statobj.st_size if encoding: response["Content-Encoding"] = encoding return response |
