Code to get categories as JSON

This commit is contained in:
Kovid Goyal 2015-11-18 12:44:02 +05:30
parent 16f80aed36
commit ebc641d894
2 changed files with 25 additions and 2 deletions

View File

@ -13,7 +13,7 @@ from calibre import prepare_string_for_xml, as_unicode
from calibre.db.view import sanitize_sort_field_name
from calibre.srv.ajax import get_db, search_result
from calibre.srv.errors import HTTPNotFound, HTTPBadRequest
from calibre.srv.metadata import book_as_json
from calibre.srv.metadata import book_as_json, categories_as_json
from calibre.srv.routes import endpoint, json
from calibre.utils.icu import sort_key
from calibre.utils.search_query_parser import ParseException
@ -118,7 +118,7 @@ def interface_data(ctx, rd):
sanitize_sort_field_name(db.field_metadata, k), v) for k, v in sf.iteritems()),
key=lambda (field, name):sort_key(name))
ans['field_metadata'] = db.field_metadata.all_metadata()
# ans['categories'] = ctx.get_categories(rd, db)
ans['categories'] = categories_as_json(ctx.get_categories(rd, db))
mdata = ans['metadata'] = {}
for book_id in ans['search_result']['book_ids']:
data = book_as_json(db, book_id)

View File

@ -7,6 +7,7 @@ from __future__ import (unicode_literals, division, absolute_import,
from datetime import datetime, time
from calibre.utils.date import isoformat, UNDEFINED_DATE, local_tz
from calibre.utils.icu import sort_key, collation_order
IGNORED_FIELDS = frozenset('cover ondevice path marked id au_map'.split())
@ -41,3 +42,25 @@ def book_as_json(db, book_id):
if field not in IGNORED_FIELDS:
add_field(field, db, book_id, ans, fm[field])
return ans
def category_item_as_json(x):
sname = x.sort or x.name
ans = {'sort_key': tuple(bytearray(sort_key(sname))), 'first_letter_sort_key': collation_order(icu_upper(sname or ' '))}
for k in x.__slots__:
if k != 'state':
val = getattr(x, k)
if isinstance(val, set):
val = tuple(val)
if val is not None:
ans[k] = val
if ans.get('sort', False) == ans['name']:
del ans['sort']
return ans
def categories_as_json(categories):
ans = []
f = category_item_as_json
for category in sorted(categories, key=sort_key):
items = tuple(f(x) for x in categories[category])
ans.append((category, items))
return ans