Ticket #1484: 1484.trunk.diff

File 1484.trunk.diff, 5.9 KB (added by Maniac <Maniac@…>, 9 years ago)

Patch for trunk

  • django/utils/httpwrappers.py

     
    22from pprint import pformat
    33from urllib import urlencode
    44from django.utils.datastructures import MultiValueDict
     5import cgi
     6from StringIO import StringIO
    57
    68try:
    79    # The mod_python version is more efficient, so try importing it first.
     
    3234    def get_full_path(self):
    3335        return ''
    3436
    35 def parse_file_upload(header_dict, post_data):
     37class FileDict(dict):
     38    "Keeps uploaded file as file-like object and reads its content on demand"
     39    def __getitem__(self, name):
     40        if name=='content' and not 'content' in self:
     41            self['file'].seek(0, 2)
     42            size = self['file'].tell()
     43            self['file'].seek(0, 0)
     44            self['content']=self['file'].read(size)
     45        return dict.__getitem__(self, name)
     46
     47class FieldStorage(cgi.FieldStorage):
     48    "cgi.FieldStorage with ability to store files on disk or in memory"
     49    def make_file(self, binary=None):
     50        from django.conf.settings import STORE_UPLOAD_ON_DISK
     51        if STORE_UPLOAD_ON_DISK:
     52            return cgi.FieldStorage.make_file(self, binary)
     53        else:
     54            return StringIO()
     55
     56def parse_file_upload(post_stream, environ):
    3657    "Returns a tuple of (POST MultiValueDict, FILES MultiValueDict)"
    37     import email, email.Message
    38     from cgi import parse_header
    39     raw_message = '\r\n'.join(['%s:%s' % pair for pair in header_dict.items()])
    40     raw_message += '\r\n\r\n' + post_data
    41     msg = email.message_from_string(raw_message)
     58    fs = FieldStorage(post_stream, environ=environ)
    4259    POST = MultiValueDict()
    4360    FILES = MultiValueDict()
    44     for submessage in msg.get_payload():
    45         if isinstance(submessage, email.Message.Message):
    46             name_dict = parse_header(submessage['Content-Disposition'])[1]
    47             # name_dict is something like {'name': 'file', 'filename': 'test.txt'} for file uploads
    48             # or {'name': 'blah'} for POST fields
    49             # We assume all uploaded files have a 'filename' set.
    50             if name_dict.has_key('filename'):
    51                 assert type([]) != type(submessage.get_payload()), "Nested MIME messages are not supported"
    52                 if not name_dict['filename'].strip():
     61    for key in fs.keys():
     62        for value in fs.getlist(key):
     63            if hasattr(fs[key], 'filename'):
     64                if not fs[key].filename.strip():
    5365                    continue
    5466                # IE submits the full path, so trim everything but the basename.
    5567                # (We can't use os.path.basename because it expects Linux paths.)
    56                 filename = name_dict['filename'][name_dict['filename'].rfind("\\")+1:]
    57                 FILES.appendlist(name_dict['name'], {
     68                filename = fs[key].filename[fs[key].filename.rfind("\\")+1:]
     69                FILES.appendlist(fs[key].name, FileDict({
    5870                    'filename': filename,
    59                     'content-type': (submessage.has_key('Content-Type') and submessage['Content-Type'] or None),
    60                     'content': submessage.get_payload(),
    61                 })
     71                    'content-type': fs[key].type,
     72                    'file': fs[key].file,
     73                }))
    6274            else:
    63                 POST.appendlist(name_dict['name'], submessage.get_payload())
     75                POST.appendlist(fs[key].name, value)
    6476    return POST, FILES
    6577
    6678class QueryDict(MultiValueDict):
  • django/conf/global_settings.py

     
    194194# http://psyco.sourceforge.net/
    195195ENABLE_PSYCO = False
    196196
     197# Whether to store uploaded files in temp files rather than in memory.
     198# Storing files on disk may be necessary for accepting large files.
     199STORE_UPLOAD_ON_DISK = False
     200
    197201##############
    198202# MIDDLEWARE #
    199203##############
  • django/core/handlers/wsgi.py

     
    6666        # Populates self._post and self._files
    6767        if self.environ['REQUEST_METHOD'] == 'POST':
    6868            if self.environ.get('CONTENT_TYPE', '').startswith('multipart'):
    69                 header_dict = dict([(k, v) for k, v in self.environ.items() if k.startswith('HTTP_')])
    70                 header_dict['Content-Type'] = self.environ.get('CONTENT_TYPE', '')
    71                 self._post, self._files = httpwrappers.parse_file_upload(header_dict, self.raw_post_data)
     69                self._post, self._files = httpwrappers.parse_file_upload(self.environ['wsgi.input'], self.environ)
    7270            else:
    7371                self._post, self._files = httpwrappers.QueryDict(self.raw_post_data), datastructures.MultiValueDict()
    7472        else:
  • django/core/handlers/modpython.py

     
    2323    def _load_post_and_files(self):
    2424        "Populates self._post and self._files"
    2525        if self._req.headers_in.has_key('content-type') and self._req.headers_in['content-type'].startswith('multipart'):
    26             self._post, self._files = httpwrappers.parse_file_upload(self._req.headers_in, self.raw_post_data)
     26            environ = dict(self.META)
     27            environ['CONTENT_LENGTH'] = environ['HTTP_CONTENT_LENGTH']
     28            environ['CONTENT_TYPE'] = environ['HTTP_CONTENT_TYPE']
     29            self._post, self._files = httpwrappers.parse_file_upload(self._req, environ)
    2730        else:
    2831            self._post, self._files = httpwrappers.QueryDict(self.raw_post_data), datastructures.MultiValueDict()
    2932
Back to Top