Cache json encoded form of tag browser

This commit is contained in:
Kovid Goyal 2015-11-28 13:25:29 +05:30
parent 30a8f1298b
commit c28d3d5025
2 changed files with 11 additions and 5 deletions

View File

@ -6,7 +6,7 @@ from __future__ import (unicode_literals, division, absolute_import,
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2015, Kovid Goyal <kovid at kovidgoyal.net>' __copyright__ = '2015, Kovid Goyal <kovid at kovidgoyal.net>'
import os import os, json
from collections import OrderedDict from collections import OrderedDict
from importlib import import_module from importlib import import_module
from threading import Lock from threading import Lock
@ -137,7 +137,10 @@ class Context(object):
old = cache.pop(key, None) old = cache.pop(key, None)
if old is None or old[0] <= db.last_modified(): 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') 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: if len(cache) > self.CATEGORY_CACHE_SIZE:
cache.popitem(last=False) cache.popitem(last=False)
else: else:

View File

@ -18,9 +18,12 @@ default_methods = frozenset(('HEAD', 'GET'))
def json(ctx, rd, endpoint, output): def json(ctx, rd, endpoint, output):
rd.outheaders['Content-Type'] = 'application/json; charset=UTF-8' rd.outheaders['Content-Type'] = 'application/json; charset=UTF-8'
ans = jsonlib.dumps(output, ensure_ascii=False) if isinstance(output, bytes):
if not isinstance(ans, bytes): ans = output # Assume output is already UTF-8 encoded json
ans = ans.encode('utf-8') else:
ans = jsonlib.dumps(output, ensure_ascii=False)
if not isinstance(ans, bytes):
ans = ans.encode('utf-8')
return ans return ans
def route_key(route): def route_key(route):