Source

CherryPy / cherrypy / _cpreqbody.py

Diff from to

File cherrypy/_cpreqbody.py

 
 You can add your own processors for any specific or major MIME type. Simply add
 it to the :attr:`processors<cherrypy._cprequest.Entity.processors>` dict in a
-hook/tool that runs at ``on_start_resource`` or ``before_request_body``. 
+hook/tool that runs at ``on_start_resource`` or ``before_request_body``.
 Here's the built-in JSON tool for an example::
 
     def json_in(force=True, debug=False):
             \"""Read application/json data into request.json.\"""
             if not entity.headers.get("Content-Length", ""):
                 raise cherrypy.HTTPError(411)
-            
+
             body = entity.fp.read()
             try:
                 request.json = json_decode(body)
                 for pair in aparam.split(ntob(';')):
                     if not pair:
                         continue
-                    
+
                     atoms = pair.split(ntob('='), 1)
                     if len(atoms) == 1:
                         atoms.append(ntob(''))
-                    
+
                     key = unquote_plus(atoms[0]).decode(charset)
                     value = unquote_plus(atoms[1]).decode(charset)
-                    
+
                     if key in params:
                         if not isinstance(params[key], list):
                             params[key] = [params[key]]
         raise cherrypy.HTTPError(
             400, "The request entity could not be decoded. The following "
             "charsets were attempted: %s" % repr(entity.attempt_charsets))
-        
+
     # Now that all values have been successfully parsed and decoded,
     # apply them to the entity.params dict.
     for key, value in params.items():
         # is often necessary to enclose the boundary parameter values in quotes
         # on the Content-type line"
         ib = entity.content_type.params['boundary'].strip('"')
-    
+
     if not re.match("^[ -~]{0,200}[!-~]$", ib):
         raise ValueError('Invalid boundary in multipart form: %r' % (ib,))
-    
+
     ib = ('--' + ib).encode('ascii')
-    
+
     # Find the first marker
     while True:
         b = entity.readline()
         if not b:
             return
-        
+
         b = b.strip()
         if b == ib:
             break
-    
+
     # Read all parts
     while True:
         part = entity.part_class.from_fp(entity.fp, ib)
 def process_multipart_form_data(entity):
     """Read all multipart/form-data parts into entity.parts or entity.params."""
     process_multipart(entity)
-    
+
     kept_parts = []
     for part in entity.parts:
         if part.name is None:
                 # It's a file upload. Retain the whole part so consumer code
                 # has access to its .file and .filename attributes.
                 value = part
-            
+
             if part.name in entity.params:
                 if not isinstance(entity.params[part.name], list):
                     entity.params[part.name] = [entity.params[part.name]]
                 entity.params[part.name].append(value)
             else:
                 entity.params[part.name] = value
-    
+
     entity.parts = kept_parts
 
 def _old_process_multipart(entity):
     """The behavior of 3.2 and lower. Deprecated and will be changed in 3.3."""
     process_multipart(entity)
-    
+
     params = entity.params
-    
+
     for part in entity.parts:
         if part.name is None:
             key = ntou('parts')
         else:
             key = part.name
-        
+
         if part.filename is None:
             # It's a regular field
             value = part.fullvalue()
             # It's a file upload. Retain the whole part so consumer code
             # has access to its .file and .filename attributes.
             value = part
-        
+
         if key in params:
             if not isinstance(params[key], list):
                 params[key] = [params[key]]
 
 class Entity(object):
     """An HTTP request body, or MIME multipart body.
-    
+
     This class collects information about the HTTP request entity. When a
     given entity is of MIME type "multipart", each part is parsed into its own
     Entity instance, and the set of parts stored in
     :attr:`entity.parts<cherrypy._cpreqbody.Entity.parts>`.
-    
+
     Between the ``before_request_body`` and ``before_handler`` tools, CherryPy
     tries to process the request body (if any) by calling
     :func:`request.body.process<cherrypy._cpreqbody.RequestBody.process`.
     processor is still not found, then the
     :func:`default_proc<cherrypy._cpreqbody.Entity.default_proc>` method of the
     Entity is called (which does nothing by default; you can override this too).
-    
+
     CherryPy includes processors for the "application/x-www-form-urlencoded"
     type, the "multipart/form-data" type, and the "multipart" major type.
     CherryPy 3.2 processes these types almost exactly as older versions.
     case it will have ``file`` and ``filename`` attributes, or possibly a
     ``value`` attribute). Each Part is itself a subclass of
     Entity, and has its own ``process`` method and ``processors`` dict.
-    
+
     There is a separate processor for the "multipart" major type which is more
     flexible, and simply stores all multipart parts in
     :attr:`request.body.parts<cherrypy._cpreqbody.Entity.parts>`. You can
     enable it with::
-    
+
         cherrypy.request.body.processors['multipart'] = _cpreqbody.process_multipart
-    
+
     in an ``on_start_resource`` tool.
     """
-    
+
     # http://tools.ietf.org/html/rfc2046#section-4.1.2:
     # "The default character set, which must be assumed in the
     # absence of a charset parameter, is US-ASCII."
     # However, many browsers send data in utf-8 with no charset.
     attempt_charsets = ['utf-8']
     """A list of strings, each of which should be a known encoding.
-    
+
     When the Content-Type of the request body warrants it, each of the given
     encodings will be tried in order. The first one to successfully decode the
     entity without raising an error is stored as
     :attr:`entity.charset<cherrypy._cpreqbody.Entity.charset>`. This defaults
-    to ``['utf-8']`` (plus 'ISO-8859-1' for "text/\*" types, as required by 
-    `HTTP/1.1 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1>`_), 
+    to ``['utf-8']`` (plus 'ISO-8859-1' for "text/\*" types, as required by
+    `HTTP/1.1 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1>`_),
     but ``['us-ascii', 'utf-8']`` for multipart parts.
     """
-    
+
     charset = None
     """The successful decoding; see "attempt_charsets" above."""
-    
+
     content_type = None
     """The value of the Content-Type request header.
-    
+
     If the Entity is part of a multipart payload, this will be the Content-Type
     given in the MIME headers for this part.
     """
-    
+
     default_content_type = 'application/x-www-form-urlencoded'
     """This defines a default ``Content-Type`` to use if no Content-Type header
     is given. The empty string is used for RequestBody, which results in the
     declares that a part with no Content-Type defaults to "text/plain"
     (see :class:`Part<cherrypy._cpreqbody.Part>`).
     """
-    
+
     filename = None
     """The ``Content-Disposition.filename`` header, if available."""
-    
+
     fp = None
     """The readable socket file object."""
-    
+
     headers = None
     """A dict of request/multipart header names and values.
-    
+
     This is a copy of the ``request.headers`` for the ``request.body``;
     for multipart parts, it is the set of headers for that part.
     """
-    
+
     length = None
     """The value of the ``Content-Length`` header, if provided."""
-    
+
     name = None
     """The "name" parameter of the ``Content-Disposition`` header, if any."""
-    
+
     params = None
     """
     If the request Content-Type is 'application/x-www-form-urlencoded' or
     can be sent with various HTTP method verbs). This value is set between
     the 'before_request_body' and 'before_handler' hooks (assuming that
     process_request_body is True)."""
-    
+
     processors = {'application/x-www-form-urlencoded': process_urlencoded,
                   'multipart/form-data': process_multipart_form_data,
                   'multipart': process_multipart,
                   }
     """A dict of Content-Type names to processor methods."""
-    
+
     parts = None
     """A list of Part instances if ``Content-Type`` is of major type "multipart"."""
-    
+
     part_class = None
     """The class used for multipart parts.
-    
+
     You can replace this with custom subclasses to alter the processing of
     multipart parts.
     """
-    
+
     def __init__(self, fp, headers, params=None, parts=None):
         # Make an instance-specific copy of the class processors
         # so Tools, etc. can replace them per-request.
         self.processors = self.processors.copy()
-        
+
         self.fp = fp
         self.headers = headers
-        
+
         if params is None:
             params = {}
         self.params = params
-        
+
         if parts is None:
             parts = []
         self.parts = parts
-        
+
         # Content-Type
         self.content_type = headers.elements('Content-Type')
         if self.content_type:
         else:
             self.content_type = httputil.HeaderElement.from_str(
                 self.default_content_type)
-        
+
         # Copy the class 'attempt_charsets', prepending any Content-Type charset
         dec = self.content_type.params.get("charset", None)
         if dec:
                                              if c != dec]
         else:
             self.attempt_charsets = self.attempt_charsets[:]
-        
+
         # Length
         self.length = None
         clen = headers.get('Content-Length', None)
                 self.length = int(clen)
             except ValueError:
                 pass
-        
+
         # Content-Disposition
         self.name = None
         self.filename = None
                 self.filename = disp.params['filename']
                 if self.filename.startswith('"') and self.filename.endswith('"'):
                     self.filename = self.filename[1:-1]
-    
+
     # The 'type' attribute is deprecated in 3.2; remove it in 3.3.
     type = property(lambda self: self.content_type,
         doc="""A deprecated alias for :attr:`content_type<cherrypy._cpreqbody.Entity.content_type>`.""")
-    
+
     def read(self, size=None, fp_out=None):
         return self.fp.read(size, fp_out)
-    
+
     def readline(self, size=None):
         return self.fp.readline(size)
-    
+
     def readlines(self, sizehint=None):
         return self.fp.readlines(sizehint)
-    
+
     def __iter__(self):
         return self
-    
+
     def __next__(self):
         line = self.readline()
         if not line:
 
     def next(self):
         return self.__next__()
-    
+
     def read_into_file(self, fp_out=None):
         """Read the request body into fp_out (or make_file() if None). Return fp_out."""
         if fp_out is None:
             fp_out = self.make_file()
         self.read(fp_out=fp_out)
         return fp_out
-    
+
     def make_file(self):
         """Return a file-like object into which the request body will be read.
-        
+
         By default, this will return a TemporaryFile. Override as needed.
         See also :attr:`cherrypy._cpreqbody.Part.maxrambytes`."""
         return tempfile.TemporaryFile()
-    
+
     def fullvalue(self):
         """Return this entity as a string, whether stored in a file or not."""
         if self.file:
         else:
             value = self.value
         return value
-    
+
     def process(self):
         """Execute the best-match processor for the given media type."""
         proc = None
             self.default_proc()
         else:
             proc(self)
-    
+
     def default_proc(self):
         """Called if a more-specific processor is not found for the ``Content-Type``."""
         # Leave the fp alone for someone else to read. This works fine
 
 class Part(Entity):
     """A MIME part entity, part of a multipart entity."""
-    
+
     # "The default character set, which must be assumed in the absence of a
     # charset parameter, is US-ASCII."
     attempt_charsets = ['us-ascii', 'utf-8']
     """A list of strings, each of which should be a known encoding.
-    
+
     When the Content-Type of the request body warrants it, each of the given
     encodings will be tried in order. The first one to successfully decode the
     entity without raising an error is stored as
     :attr:`entity.charset<cherrypy._cpreqbody.Entity.charset>`. This defaults
-    to ``['utf-8']`` (plus 'ISO-8859-1' for "text/\*" types, as required by 
-    `HTTP/1.1 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1>`_), 
+    to ``['utf-8']`` (plus 'ISO-8859-1' for "text/\*" types, as required by
+    `HTTP/1.1 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1>`_),
     but ``['us-ascii', 'utf-8']`` for multipart parts.
     """
-    
+
     boundary = None
     """The MIME multipart boundary."""
-    
+
     default_content_type = 'text/plain'
     """This defines a default ``Content-Type`` to use if no Content-Type header
     is given. The empty string is used for RequestBody, which results in the
     the MIME spec declares that a part with no Content-Type defaults to
     "text/plain".
     """
-    
+
     # This is the default in stdlib cgi. We may want to increase it.
     maxrambytes = 1000
     """The threshold of bytes after which point the ``Part`` will store its data
     instead of a string. Defaults to 1000, just like the :mod:`cgi` module in
     Python's standard library.
     """
-    
+
     def __init__(self, fp, headers, boundary):
         Entity.__init__(self, fp, headers)
         self.boundary = boundary
         self.file = None
         self.value = None
-    
+
     def from_fp(cls, fp, boundary):
         headers = cls.read_headers(fp)
         return cls(fp, headers, boundary)
     from_fp = classmethod(from_fp)
-    
+
     def read_headers(cls, fp):
         headers = httputil.HeaderMap()
         while True:
             if not line:
                 # No more data--illegal end of headers
                 raise EOFError("Illegal end of headers.")
-            
+
             if line == ntob('\r\n'):
                 # Normal end of headers
                 break
             if not line.endswith(ntob('\r\n')):
                 raise ValueError("MIME requires CRLF terminators: %r" % line)
-            
+
             if line[0] in ntob(' \t'):
                 # It's a continuation line.
                 v = line.strip().decode('ISO-8859-1')
                 k, v = line.split(ntob(":"), 1)
                 k = k.strip().decode('ISO-8859-1')
                 v = v.strip().decode('ISO-8859-1')
-            
+
             existing = headers.get(k)
             if existing:
                 v = ", ".join((existing, v))
             headers[k] = v
-        
+
         return headers
     read_headers = classmethod(read_headers)
-    
+
     def read_lines_to_boundary(self, fp_out=None):
         """Read bytes from self.fp and return or write them to a file.
-        
+
         If the 'fp_out' argument is None (the default), all bytes read are
         returned in a single byte string.
-        
+
         If the 'fp_out' argument is not None, it must be a file-like object that
         supports the 'write' method; all bytes read will be written to the fp,
         and that fp is returned.
                 if strippedline == endmarker:
                     self.fp.finish()
                     break
-            
+
             line = delim + line
-            
+
             if line.endswith(ntob("\r\n")):
                 delim = ntob("\r\n")
                 line = line[:-2]
             else:
                 delim = ntob("")
                 prev_lf = False
-            
+
             if fp_out is None:
                 lines.append(line)
                 seen += len(line)
                         fp_out.write(line)
             else:
                 fp_out.write(line)
-        
+
         if fp_out is None:
             result = ntob('').join(lines)
             for charset in self.attempt_charsets:
         else:
             fp_out.seek(0)
             return fp_out
-    
+
     def default_proc(self):
         """Called if a more-specific processor is not found for the ``Content-Type``."""
         if self.filename:
                 self.value = result
             else:
                 self.file = result
-    
+
     def read_into_file(self, fp_out=None):
         """Read the request body into fp_out (or make_file() if None). Return fp_out."""
         if fp_out is None:
 
 
 class SizedReader:
-    
+
     def __init__(self, fp, length, maxbytes, bufsize=DEFAULT_BUFFER_SIZE, has_trailers=False):
         # Wrap our fp in a buffer so peek() works
         self.fp = fp
         self.bytes_read = 0
         self.done = False
         self.has_trailers = has_trailers
-    
+
     def read(self, size=None, fp_out=None):
         """Read bytes from the request body and return or write them to a file.
-        
+
         A number of bytes less than or equal to the 'size' argument are read
         off the socket. The actual number of bytes read are tracked in
         self.bytes_read. The number may be smaller than 'size' when 1) the
         client sends fewer bytes, 2) the 'Content-Length' request header
         specifies fewer bytes than requested, or 3) the number of bytes read
         exceeds self.maxbytes (in which case, 413 is raised).
-        
+
         If the 'fp_out' argument is None (the default), all bytes read are
         returned in a single byte string.
-        
+
         If the 'fp_out' argument is not None, it must be a file-like object that
         supports the 'write' method; all bytes read will be written to the fp,
         and None is returned.
         """
-        
+
         if self.length is None:
             if size is None:
                 remaining = inf
                 return ntob('')
             else:
                 return None
-        
+
         chunks = []
-        
+
         # Read bytes from the buffer.
         if self.buffer:
             if remaining is inf:
                 self.buffer = self.buffer[remaining:]
             datalen = len(data)
             remaining -= datalen
-            
+
             # Check lengths.
             self.bytes_read += datalen
             if self.maxbytes and self.bytes_read > self.maxbytes:
                 raise cherrypy.HTTPError(413)
-            
+
             # Store the data.
             if fp_out is None:
                 chunks.append(data)
             else:
                 fp_out.write(data)
-        
+
         # Read bytes from the socket.
         while remaining > 0:
             chunksize = min(remaining, self.bufsize)
                 break
             datalen = len(data)
             remaining -= datalen
-            
+
             # Check lengths.
             self.bytes_read += datalen
             if self.maxbytes and self.bytes_read > self.maxbytes:
                 raise cherrypy.HTTPError(413)
-            
+
             # Store the data.
             if fp_out is None:
                 chunks.append(data)
             else:
                 fp_out.write(data)
-        
+
         if fp_out is None:
             return ntob('').join(chunks)
-    
+
     def readline(self, size=None):
         """Read a line from the request body and return it."""
         chunks = []
             else:
                 chunks.append(data)
         return ntob('').join(chunks)
-    
+
     def readlines(self, sizehint=None):
         """Read lines from the request body and return them."""
         if self.length is not None:
                 sizehint = self.length - self.bytes_read
             else:
                 sizehint = min(sizehint, self.length - self.bytes_read)
-        
+
         lines = []
         seen = 0
         while True:
             if seen >= sizehint:
                 break
         return lines
-    
+
     def finish(self):
         self.done = True
         if self.has_trailers and hasattr(self.fp, 'read_trailer_lines'):
             self.trailers = {}
-            
+
             try:
                 for line in self.fp.read_trailer_lines():
                     if line[0] in ntob(' \t'):
                             raise ValueError("Illegal header line.")
                         k = k.strip().title()
                         v = v.strip()
-                    
+
                     if k in comma_separated_headers:
                         existing = self.trailers.get(envname)
                         if existing:
 
 class RequestBody(Entity):
     """The entity of the HTTP request."""
-    
+
     bufsize = 8 * 1024
     """The buffer size used when reading the socket."""
-    
+
     # Don't parse the request body at all if the client didn't provide
     # a Content-Type header. See http://www.cherrypy.org/ticket/790
     default_content_type = ''
     declares that a part with no Content-Type defaults to "text/plain"
     (see :class:`Part<cherrypy._cpreqbody.Part>`).
     """
-    
+
     maxbytes = None
     """Raise ``MaxSizeExceeded`` if more bytes than this are read from the socket."""
-    
+
     def __init__(self, fp, headers, params=None, request_params=None):
         Entity.__init__(self, fp, headers, params)
-        
+
         # http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1
         # When no explicit charset parameter is provided by the
         # sender, media subtypes of the "text" type are defined
                     break
             else:
                 self.attempt_charsets.append('ISO-8859-1')
-        
+
         # Temporary fix while deprecating passing .parts as .params.
         self.processors['multipart'] = _old_process_multipart
-        
+
         if request_params is None:
             request_params = {}
         self.request_params = request_params
-    
+
     def process(self):
         """Process the request entity based on its Content-Type."""
         # "The presence of a message-body in a request is signaled by the
         h = cherrypy.serving.request.headers
         if 'Content-Length' not in h and 'Transfer-Encoding' not in h:
             raise cherrypy.HTTPError(411)
-        
+
         self.fp = SizedReader(self.fp, self.length,
                               self.maxbytes, bufsize=self.bufsize,
                               has_trailers='Trailer' in h)
         super(RequestBody, self).process()
-        
+
         # Body params should also be a part of the request_params
         # add them in here.
         request_params = self.request_params
             if sys.version_info < (3, 0):
                 if isinstance(key, unicode):
                     key = key.encode('ISO-8859-1')
-            
+
             if key in request_params:
                 if not isinstance(request_params[key], list):
                     request_params[key] = [request_params[key]]