jsontools.py (1959B)
1 #Embedded file name: C:\BuildAgent\work\20d73f1b24eed06e\eve\release\V24.01\carbon\common\lib\cherrypy\lib\jsontools.py 2 import sys 3 import cherrypy 4 from cherrypy._cpcompat import basestring, ntou, json, json_encode, json_decode 5 6 def json_processor(entity): 7 if not entity.headers.get(ntou('Content-Length'), ntou('')): 8 raise cherrypy.HTTPError(411) 9 body = entity.fp.read() 10 try: 11 cherrypy.serving.request.json = json_decode(body.decode('utf-8')) 12 except ValueError: 13 raise cherrypy.HTTPError(400, 'Invalid JSON document') 14 15 16 def json_in(content_type = [ntou('application/json'), ntou('text/javascript')], force = True, debug = False, processor = json_processor): 17 request = cherrypy.serving.request 18 if isinstance(content_type, basestring): 19 content_type = [content_type] 20 if force: 21 if debug: 22 cherrypy.log('Removing body processors %s' % repr(request.body.processors.keys()), 'TOOLS.JSON_IN') 23 request.body.processors.clear() 24 request.body.default_proc = cherrypy.HTTPError(415, 'Expected an entity of content type %s' % ', '.join(content_type)) 25 for ct in content_type: 26 if debug: 27 cherrypy.log('Adding body processor for %s' % ct, 'TOOLS.JSON_IN') 28 request.body.processors[ct] = processor 29 30 31 def json_handler(*args, **kwargs): 32 value = cherrypy.serving.request._json_inner_handler(*args, **kwargs) 33 return json_encode(value) 34 35 36 def json_out(content_type = 'application/json', debug = False, handler = json_handler): 37 request = cherrypy.serving.request 38 if debug: 39 cherrypy.log('Replacing %s with JSON handler' % request.handler, 'TOOLS.JSON_OUT') 40 request._json_inner_handler = request.handler 41 request.handler = handler 42 if content_type is not None: 43 if debug: 44 cherrypy.log('Setting Content-Type to %s' % ct, 'TOOLS.JSON_OUT') 45 cherrypy.serving.response.headers['Content-Type'] = content_type