Skip to content

Commit

Permalink
[#1078] LazyJSONEncoder as fallback for api call responses
Browse files Browse the repository at this point in the history
  • Loading branch information
wardi committed Sep 4, 2013
1 parent 44aa969 commit 3ae69be
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 7 deletions.
13 changes: 6 additions & 7 deletions ckan/controllers/api.py
Expand Up @@ -16,6 +16,7 @@
import ckan.lib.navl.dictization_functions
import ckan.lib.jsonp as jsonp
import ckan.lib.munge as munge
import ckan.lib.lazyjson as lazyjson

from ckan.common import _, c, request, response

Expand All @@ -34,7 +35,6 @@
'text': 'text/plain;charset=utf-8',
'html': 'text/html;charset=utf-8',
'json': 'application/json;charset=utf-8',
'json_string': 'application/json;charset=utf-8',
}


Expand Down Expand Up @@ -83,7 +83,11 @@ def _finish(self, status_int, response_data=None,
if response_data is not None:
response.headers['Content-Type'] = CONTENT_TYPES[content_type]
if content_type == 'json':
response_msg = h.json.dumps(response_data)
try:
response_msg = h.json.dumps(response_data)
except TypeError:
response_msg = lazyjson.LazyJSONEncoder().encode(
response_data)
else:
response_msg = response_data
# Support "JSONP" callback.
Expand Down Expand Up @@ -186,11 +190,6 @@ def action(self, logic_function, ver=None):
try:
result = function(context, request_data)
return_dict['success'] = True
if hasattr(result, 'to_json_string'):
return_dict['result'] = 463455395108 # magic placeholder
return self._finish_ok(h.json.dumps(
return_dict).replace('463455395108',
result.to_json_string()), 'json_string')
return_dict['result'] = result
except DataError, e:
log.error('Format incorrect: %s - %s' % (e.error, request_data))
Expand Down
6 changes: 6 additions & 0 deletions ckan/lib/lazyjson.py
Expand Up @@ -34,3 +34,9 @@ def method(self, *args, **kwargs):
setattr(LazyJSONObject, fn, _loads_method(fn))


class LazyJSONEncoder(json.JSONEncoder):
'''JSON encoder that handles LazyJSONObject elements'''
def _iterencode_default(self, o, markers=None):
if hasattr(o, 'to_json_string'):
return iter([o.to_json_string()])
return json.JSONEncoder._iterencode_default(self, o, markers)

0 comments on commit 3ae69be

Please sign in to comment.