本文整理汇总了Python中calibre.ebooks.metadata.book.json_codec.JsonCodec.encode_book_metadata方法的典型用法代码示例。如果您正苦于以下问题:Python JsonCodec.encode_book_metadata方法的具体用法?Python JsonCodec.encode_book_metadata怎么用?Python JsonCodec.encode_book_metadata使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类calibre.ebooks.metadata.book.json_codec.JsonCodec
的用法示例。
在下文中一共展示了JsonCodec.encode_book_metadata方法的3个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: AjaxServer
# 需要导入模块: from calibre.ebooks.metadata.book.json_codec import JsonCodec [as 别名]
# 或者: from calibre.ebooks.metadata.book.json_codec.JsonCodec import encode_book_metadata [as 别名]
class AjaxServer(object):
def __init__(self):
self.ajax_json_codec = JsonCodec()
def add_routes(self, connect):
base_href = '/ajax'
# Metadata for books
connect('ajax_book', base_href+'/book/{book_id}', self.ajax_book)
connect('ajax_books', base_href+'/books', self.ajax_books)
# The list of top level categories
connect('ajax_categories', base_href+'/categories',
self.ajax_categories)
# The list of sub-categories and items in each category
connect('ajax_category', base_href+'/category/{name}',
self.ajax_category)
# List of books in specified category
connect('ajax_books_in', base_href+'/books_in/{category}/{item}',
self.ajax_books_in)
# Search
connect('ajax_search', base_href+'/search', self.ajax_search)
# Get book metadata {{{
def ajax_book_to_json(self, book_id, get_category_urls=True,
device_compatible=False, device_for_template=None):
mi = self.db.get_metadata(book_id, index_is_id=True)
if not device_compatible:
try:
mi.rating = mi.rating/2.
except:
mi.rating = 0.0
data = self.ajax_json_codec.encode_book_metadata(mi)
for x in ('publication_type', 'size', 'db_id', 'lpath', 'mime',
'rights', 'book_producer'):
data.pop(x, None)
data['cover'] = absurl(self.opts.url_prefix, u'/get/cover/%d'%book_id)
data['thumbnail'] = absurl(self.opts.url_prefix, u'/get/thumb/%d'%book_id)
if not device_compatible:
mi.format_metadata = {k.lower():dict(v) for k, v in
mi.format_metadata.iteritems()}
for v in mi.format_metadata.itervalues():
mtime = v.get('mtime', None)
if mtime is not None:
v['mtime'] = isoformat(mtime, as_utc=True)
data['format_metadata'] = mi.format_metadata
fmts = set(x.lower() for x in mi.format_metadata.iterkeys())
pf = prefs['output_format'].lower()
other_fmts = list(fmts)
try:
fmt = pf if pf in fmts else other_fmts[0]
except:
fmt = None
if fmts and fmt:
other_fmts = [x for x in fmts if x != fmt]
data['formats'] = sorted(fmts)
if fmt:
data['main_format'] = {fmt: absurl(self.opts.url_prefix, u'/get/%s/%d'%(fmt, book_id))}
else:
data['main_format'] = None
data['other_formats'] = {fmt: absurl(self.opts.url_prefix, u'/get/%s/%d'%(fmt, book_id)) for fmt
in other_fmts}
if get_category_urls:
category_urls = data['category_urls'] = {}
ccache = self.categories_cache()
for key in mi.all_field_keys():
fm = mi.metadata_for_field(key)
if (fm and fm['is_category'] and not fm['is_csp'] and
key != 'formats' and fm['datatype'] not in ['rating']):
categories = mi.get(key)
if isinstance(categories, basestring):
categories = [categories]
if categories is None:
categories = []
dbtags = {}
for category in categories:
for tag in ccache.get(key, []):
if tag.original_name == category:
dbtags[category] = books_in_url(self.opts.url_prefix,
tag.category if tag.category else key,
tag.original_name if tag.id is None else
unicode(tag.id))
break
category_urls[key] = dbtags
else:
series = data.get('series', None)
if series:
tsorder = tweaks['save_template_title_series_sorting']
series = title_sort(series, order=tsorder)
else:
series = ''
#.........这里部分代码省略.........
示例2: book_to_json
# 需要导入模块: from calibre.ebooks.metadata.book.json_codec import JsonCodec [as 别名]
# 或者: from calibre.ebooks.metadata.book.json_codec.JsonCodec import encode_book_metadata [as 别名]
def book_to_json(ctx, rd, db, book_id,
get_category_urls=True, device_compatible=False, device_for_template=None):
mi = db.get_metadata(book_id, get_cover=False)
codec = JsonCodec(db.field_metadata)
if not device_compatible:
try:
mi.rating = mi.rating/2.
except Exception:
mi.rating = 0.0
data = codec.encode_book_metadata(mi)
for x in ('publication_type', 'size', 'db_id', 'lpath', 'mime',
'rights', 'book_producer'):
data.pop(x, None)
get = partial(ctx.url_for, get_content, book_id=book_id, library_id=db.server_library_id)
data['cover'] = get(what='cover')
data['thumbnail'] = get(what='thumb')
if not device_compatible:
mi.format_metadata = {k.lower():dict(v) for k, v in
mi.format_metadata.iteritems()}
for v in mi.format_metadata.itervalues():
mtime = v.get('mtime', None)
if mtime is not None:
v['mtime'] = isoformat(mtime, as_utc=True)
data['format_metadata'] = mi.format_metadata
fmts = set(x.lower() for x in mi.format_metadata.iterkeys())
pf = prefs['output_format'].lower()
other_fmts = list(fmts)
try:
fmt = pf if pf in fmts else other_fmts[0]
except:
fmt = None
if fmts and fmt:
other_fmts = [x for x in fmts if x != fmt]
data['formats'] = sorted(fmts)
if fmt:
data['main_format'] = {fmt:get(what=fmt)}
else:
data['main_format'] = None
data['other_formats'] = {fmt:get(what=fmt) for fmt in other_fmts}
if get_category_urls:
category_urls = data['category_urls'] = {}
all_cats = ctx.get_categories(rd, db)
for key in mi.all_field_keys():
fm = mi.metadata_for_field(key)
if (fm and fm['is_category'] and not fm['is_csp'] and
key != 'formats' and fm['datatype'] != 'rating'):
categories = mi.get(key) or []
if isinstance(categories, basestring):
categories = [categories]
category_urls[key] = dbtags = {}
for category in categories:
for tag in all_cats.get(key, ()):
if tag.original_name == category:
dbtags[category] = ctx.url_for(
books_in,
encoded_category=encode_name(tag.category if tag.category else key),
encoded_item=encode_name(tag.original_name if tag.id is None else unicode(tag.id)),
library_id=db.server_library_id
)
break
else:
series = data.get('series', None) or ''
if series:
tsorder = tweaks['save_template_title_series_sorting']
series = title_sort(series, order=tsorder)
data['_series_sort_'] = series
if device_for_template:
import posixpath
from calibre.devices.utils import create_upload_path
from calibre.utils.filenames import ascii_filename as sanitize
from calibre.customize.ui import device_plugins
for device_class in device_plugins():
if device_class.__class__.__name__ == device_for_template:
template = device_class.save_template()
data['_filename_'] = create_upload_path(mi, book_id,
template, sanitize, path_type=posixpath)
break
return data, mi.last_modified
示例3: BrowseServer
# 需要导入模块: from calibre.ebooks.metadata.book.json_codec import JsonCodec [as 别名]
# 或者: from calibre.ebooks.metadata.book.json_codec.JsonCodec import encode_book_metadata [as 别名]
#.........这里部分代码省略.........
elif meta['is_custom']:
icon = category_icon_map['custom:']
elif meta['kind'] == 'user':
icon = category_icon_map['user:']
else:
icon = 'check_box_outline_blank'
if meta['kind'] == 'user':
dot = category.find('.')
if dot > 0:
cat = category[:dot]
if cat not in uc_displayed:
cats.append((meta['name'][:dot-1], cat, icon))
uc_displayed.add(cat)
else:
cats.append((meta['name'], category, icon))
uc_displayed.add(category)
else:
cats.append((meta['name'], category, icon))
cats = [(u'<li><a title="{2} {0}" href="{3}/browse/category/{1}">'
u'<i class="material-icons">{icon}</i>'
u'<span>{0}</span></a>'
u'</li>')
.format(xml(name, True), xml(quote(cat)), xml(_('Browse books by')),
self.opts.url_prefix, icon=icon)
for name, cat, icon in cats]
return '\n'.join(cats)
def books_to_json(self, *books):
result = []
for book in books:
book_json = self.json_codec.encode_book_metadata(book)
book_json['formats'] = [fmt.lower() for fmt in book.formats]
book_json['format_metadata'] = {k.lower(): dict(v) for k, v in book.format_metadata.iteritems()}
for v in book_json['format_metadata'].itervalues():
v.pop('mtime', None)
result.append(book_json)
return json.dumps(result, skipkeys=True)
def browse_json_books(self, ids, prefix, suffix=''):
books = [self.db.get_metadata(id, True) for id in ids]
books_json = self.books_to_json(*books)
return "<script>window.calibre_books = {}</script>".format(books_json)
def browse_toplevel(self):
main = u'<div class="toplevel"></div>'
return self.browse_template('name').format(title='', main=main)
def browse_sort_categories(self, items, sort):
if sort not in ('rating', 'name', 'popularity'):
sort = 'name'
items.sort(key=lambda x: sort_key(getattr(x, 'sort', x.name)))
if sort == 'popularity':
items.sort(key=operator.attrgetter('count'), reverse=True)
elif sort == 'rating':
items.sort(key=operator.attrgetter('avg_rating'), reverse=True)
return sort
def browse_category(self, category, sort):
categories = self.categories_cache()
categories['virt_libs'] = {}
if category not in categories:
raise cherrypy.HTTPError(404, 'category not found')
category_meta = self.db.field_metadata