1 # -*- coding: utf-8 -*-
3 # This file is part of FNP-Redakcja, licensed under GNU Affero GPLv3 or later.
4 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
7 Abstraction over API for wolnelektury.pl
13 logger = logging.getLogger("fnp.lib.wlapi")
16 class APICallException(Exception):
18 def __init__(self, cause=None):
19 super(Exception, self).__init__()
22 def __unicode__(self):
23 return u"%s, cause: %s" % (type(self).__name__, repr(self.cause))
26 return self.__unicode__().encode('utf-8')
29 def api_call(path, format="json"):
32 @functools.wraps(func)
33 def wrapped(self, *args, **kwargs):
34 generator = func(self, *args, **kwargs)
36 data = generator.next()
39 rq = urllib2.Request(self.base_url + path + ".json")
41 # will send POST when there is data, GET otherwise
43 rq.add_data(json.dumps(data))
44 rq.add_header("Content-Type", "application/json")
47 anwser = json.load(self.opener.open(rq))
49 return generator.send(anwser)
51 # by default, just return the anwser as a shorthand
53 except urllib2.HTTPError, error:
54 return self._http_error(error)
55 except Exception, error:
56 return self._error(error)
64 def __init__(self, **config_dict):
65 self.base_url = config_dict['URL']
66 self.auth_realm = config_dict['AUTH_REALM']
67 self.auth_user = config_dict['AUTH_USER']
69 digest_handler = urllib2.HTTPDigestAuthHandler()
70 digest_handler.add_password(
71 realm=self.auth_realm, uri=self.base_url,
72 user=self.auth_user, passwd=config_dict['AUTH_PASSWD'])
74 basic_handler = urllib2.HTTPBasicAuthHandler()
75 basic_handler.add_password(
76 realm=self.auth_realm, uri=self.base_url,
77 user=self.auth_user, passwd=config_dict['AUTH_PASSWD'])
79 self.opener = urllib2.build_opener(digest_handler, basic_handler)
81 def _http_error(self, error):
82 message = error.read()
83 logger.debug("HTTP ERROR: %s", message)
84 return self._error(message)
86 def _error(self, error):
87 raise APICallException(error)
94 def publish_book(self, document):
95 yield {"text": document.text, "compressed": False}