Allow using references to the function in url_for() instead of just the route key

This commit is contained in:
Kovid Goyal 2015-06-15 10:43:34 +05:30
parent 5dba5f88a4
commit 52b16e4f4b
2 changed files with 8 additions and 2 deletions

View File

@ -16,7 +16,6 @@ from calibre.ebooks.metadata import authors_to_string
from calibre.ebooks.metadata.meta import set_metadata
from calibre.ebooks.metadata.opf2 import metadata_to_opf
from calibre.library.save_to_disk import find_plugboard
from calibre.srv.ajax import book_to_json
from calibre.srv.errors import HTTPNotFound
from calibre.srv.routes import endpoint, json
from calibre.srv.utils import http_date
@ -234,6 +233,7 @@ def get(ctx, rd, what, book_id, library_id):
rd.outheaders['Last-Modified'] = http_date(timestampfromdt(mi.last_modified))
return metadata_to_opf(mi)
elif what == 'json':
from calibre.srv.ajax import book_to_json
data, last_modified = book_to_json(ctx, rd, db, book_id)
rd.outheaders['Last-Modified'] = http_date(timestampfromdt(last_modified))
return json(ctx, rd, get, data)

View File

@ -43,6 +43,7 @@ def endpoint(route,
):
def annotate(f):
f.route = route.rstrip('/') or '/'
f.route_key = route_key(f.route)
f.types = types or {}
f.methods = methods
f.auth_required = auth_required
@ -172,15 +173,19 @@ class Router(object):
self.auth_controller = auth_controller
self.init_session = getattr(ctx, 'init_session', lambda ep, data:None)
self.finalize_session = getattr(ctx, 'finalize_session', lambda ep, data, output:None)
self.endpoints = set()
if endpoints is not None:
self.load_routes(endpoints)
self.finalize()
def add(self, endpoint):
key = route_key(endpoint.route)
if endpoint in self.endpoints:
return
key = endpoint.route_key
if key in self.routes:
raise RouteError('A route with the key: %s already exists as: %s' % (key, self.routes[key]))
self.routes[key] = Route(endpoint)
self.endpoints.add(endpoint)
def load_routes(self, items):
for item in items:
@ -270,4 +275,5 @@ class Router(object):
return ans
def url_for(self, route, **kwargs):
route = getattr(route, 'route_key', route)
return self.url_prefix + self.routes[route].url_for(**kwargs)