diff --git a/src/calibre/srv/handler.py b/src/calibre/srv/handler.py index 98122960f5..e25c74f566 100644 --- a/src/calibre/srv/handler.py +++ b/src/calibre/srv/handler.py @@ -6,7 +6,7 @@ from __future__ import (unicode_literals, division, absolute_import, __license__ = 'GPL v3' __copyright__ = '2015, Kovid Goyal ' -import os +import os, json from collections import OrderedDict from importlib import import_module from threading import Lock @@ -137,7 +137,10 @@ class Context(object): old = cache.pop(key, None) if old is None or old[0] <= db.last_modified(): categories = db.get_categories(book_ids=restrict_to_ids, sort=opts.sort_by, first_letter_sort=opts.collapse_model == 'first letter') - cache[key] = old = (utcnow(), render(db, categories)) + data = json.dumps(render(db, categories), ensure_ascii=False) + if isinstance(data, type('')): + data = data.encode('utf-8') + cache[key] = old = (utcnow(), data) if len(cache) > self.CATEGORY_CACHE_SIZE: cache.popitem(last=False) else: diff --git a/src/calibre/srv/routes.py b/src/calibre/srv/routes.py index d323d216f4..66d482b47b 100644 --- a/src/calibre/srv/routes.py +++ b/src/calibre/srv/routes.py @@ -18,9 +18,12 @@ default_methods = frozenset(('HEAD', 'GET')) def json(ctx, rd, endpoint, output): rd.outheaders['Content-Type'] = 'application/json; charset=UTF-8' - ans = jsonlib.dumps(output, ensure_ascii=False) - if not isinstance(ans, bytes): - ans = ans.encode('utf-8') + if isinstance(output, bytes): + ans = output # Assume output is already UTF-8 encoded json + else: + ans = jsonlib.dumps(output, ensure_ascii=False) + if not isinstance(ans, bytes): + ans = ans.encode('utf-8') return ans def route_key(route):