diff options
author | alex.morega <none@none> | 2009-04-01 23:55:30 +0000 |
---|---|---|
committer | alex.morega <none@none> | 2009-04-01 23:55:30 +0000 |
commit | ce5464706681a161cbf1dd02ca0ffe23ca55a7f5 (patch) | |
tree | c30013334319103a4e3c45d5e7c0dcc280e5af42 /cherrypy/lib/jsontools.py | |
parent | 70cd9afa290c30f48f3fb75850047eec29513297 (diff) | |
download | cherrypy-git-ce5464706681a161cbf1dd02ca0ffe23ca55a7f5.tar.gz |
json support: better import logic (#831)
Diffstat (limited to 'cherrypy/lib/jsontools.py')
-rw-r--r-- | cherrypy/lib/jsontools.py | 32 |
1 files changed, 19 insertions, 13 deletions
diff --git a/cherrypy/lib/jsontools.py b/cherrypy/lib/jsontools.py index 17cd8a1e..e71874a8 100644 --- a/cherrypy/lib/jsontools.py +++ b/cherrypy/lib/jsontools.py @@ -1,13 +1,24 @@ import cherrypy -json_codecs = {} +try: + # Python 2.6: simplejson is part of the standard library + import json +except ImportError: + try: + import simplejson as json + except ImportError: + json = None + +if json is None: + def json_decode(s): + raise ValueError('No JSON library is available') + def json_encode(s): + raise ValueError('No JSON library is available') +else: + json_decode = json.JSONDecoder().decode + json_encode = json.JSONEncoder().iterencode def json_in(*args, **kwargs): - if 'decoder' not in json_codecs: - # we don't want to import simplejson until we're sure we need it - from simplejson import JSONDecoder - json_codecs['decoder'] = JSONDecoder() - request = cherrypy.request _h = request.headers if ('Content-Type' not in _h @@ -18,18 +29,13 @@ def json_in(*args, **kwargs): body = request.body.read(length) try: - json = json_codecs['decoder'].decode(body) + json = json_decode(body) except ValueError: raise cherrypy.HTTPError(400, 'Invalid JSON document') request.json = json def json_out(*args, **kwargs): - if 'encoder' not in json_codecs: - # we don't want to import simplejson until we're sure we need it - from simplejson import JSONEncoder - json_codecs['encoder'] = JSONEncoder() - request = cherrypy.request response = cherrypy.response @@ -37,5 +43,5 @@ def json_out(*args, **kwargs): def json_handler(*args, **kwargs): response.headers['Content-Type'] = 'application/json' value = real_handler(*args, **kwargs) - return json_codecs['encoder'].iterencode(value) + return json_encode(value) request.handler = json_handler |