Download Install Tutorial Docs FAQ Tools WikiLicense Team IRC Planet Involvement Shop Book

root/branches/cherrypy-2.x/cherrypy/filters/decodingfilter.py

Revision 946 (checked in by fumanchu, 3 years ago)

Fixes for header.elements now returning [] instead of None.

  • Property svn:eol-style set to native
Line 
1 import cherrypy
2 from basefilter import BaseFilter
3
4 class DecodingFilter(BaseFilter):
5     """Automatically decodes request parameters (except uploads)."""
6    
7     def before_main(self):
8         conf = cherrypy.config.get
9        
10         if not conf('decoding_filter.on', False):
11             return
12        
13         enc = conf('decoding_filter.encoding', None)
14         if not enc:
15             ct = cherrypy.request.headers.elements("Content-Type")
16             if ct:
17                 ct = ct[0]
18                 enc = ct.params.get("charset", None)
19                 if (not enc) and ct.value.lower().startswith("text/"):
20                     # http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1
21                     # When no explicit charset parameter is provided by the
22                     # sender, media subtypes of the "text" type are defined
23                     # to have a default charset value of "ISO-8859-1" when
24                     # received via HTTP.
25                     enc = "ISO-8859-1"
26            
27             if not enc:
28                 enc = conf('decoding_filter.default_encoding', "utf-8")
29        
30         try:
31             self.decode(enc)
32         except UnicodeDecodeError:
33             # IE and Firefox don't supply a charset when submitting form
34             # params with a CT of application/x-www-form-urlencoded.
35             # So after all our guessing, it could *still* be wrong.
36             # Start over with ISO-8859-1, since that seems to be preferred.
37             self.decode("ISO-8859-1")
38    
39     def decode(self, enc):
40         decodedParams = {}
41         for key, value in cherrypy.request.params.items():
42             if hasattr(value, 'file'):
43                 # This is a file being uploaded: skip it
44                 decodedParams[key] = value
45             elif isinstance(value, list):
46                 # value is a list: decode each element
47                 decodedParams[key] = [v.decode(enc) for v in value]
48             else:
49                 # value is a regular string: decode it
50                 decodedParams[key] = value.decode(enc)
51        
52         # Decode all or nothing, so we can try again on error.
53         cherrypy.request.params = decodedParams
54
Note: See TracBrowser for help on using the browser.

Hosted by WebFaction

Log in as guest/cpguest to create tickets