1 import cherrypy
2 from cherrypy._cpcompat import basestring, ntou, json_encode, json_decode
3
4
15
16
19 """Add a processor to parse JSON request entities:
20 The default processor places the parsed data into request.json.
21
22 Incoming request entities which match the given content_type(s) will
23 be deserialized from JSON to the Python equivalent, and the result
24 stored at cherrypy.request.json. The 'content_type' argument may
25 be a Content-Type string or a list of allowable Content-Type strings.
26
27 If the 'force' argument is True (the default), then entities of other
28 content types will not be allowed; "415 Unsupported Media Type" is
29 raised instead.
30
31 Supply your own processor to use a custom decoder, or to handle the parsed
32 data differently. The processor can be configured via
33 tools.json_in.processor or via the decorator method.
34
35 Note that the deserializer requires the client send a Content-Length
36 request header, or it will raise "411 Length Required". If for any
37 other reason the request entity cannot be deserialized from JSON,
38 it will raise "400 Bad Request: Invalid JSON document".
39
40 You must be using Python 2.6 or greater, or have the 'simplejson'
41 package importable; otherwise, ValueError is raised during processing.
42 """
43 request = cherrypy.serving.request
44 if isinstance(content_type, basestring):
45 content_type = [content_type]
46
47 if force:
48 if debug:
49 cherrypy.log('Removing body processors %s' %
50 repr(request.body.processors.keys()), 'TOOLS.JSON_IN')
51 request.body.processors.clear()
52 request.body.default_proc = cherrypy.HTTPError(
53 415, 'Expected an entity of content type %s' %
54 ', '.join(content_type))
55
56 for ct in content_type:
57 if debug:
58 cherrypy.log('Adding body processor for %s' % ct, 'TOOLS.JSON_IN')
59 request.body.processors[ct] = processor
60
61
65
66
97