2 Abstraction over API for wolnelektury.pl
6 import django.utils.simplejson as json
8 logger = logging.getLogger("fnp.lib.wlapi")
10 class APICallException(Exception):
13 def api_call(path, format="json"):
16 @functools.wraps(func)
17 def wrapped(self, *args, **kwargs):
18 generator = func(self, *args, **kwargs)
20 data = generator.next()
23 rq = urllib2.Request(self.base_url + path + ".json")
25 # will send POST when there is data, GET otherwise
27 rq.add_data(json.dumps(data))
28 rq.add_header("Content-Type", "application/json")
31 anwser = json.load(self.opener.open(rq))
32 return generator.send(anwser)
34 # by default, just return the anwser as a shorthand
36 except urllib2.HTTPError, error:
37 return self._http_error(error)
38 except Exception, error:
39 return self._error(error)
48 def __init__(self, config_dict):
49 self.base_url = config_dict['URL']
50 self.auth_realm = config_dict['AUTH_REALM']
51 self.auth_user = config_dict['AUTH_USER']
53 auth_handler = urllib2.HTTPDigestAuthHandler();
54 auth_handler.add_password(
55 realm=self.auth_realm, uri=self.base_url,
56 user=self.auth_user, passwd=config_dict['AUTH_PASSWD'])
58 self.opener = urllib2.build_opener(auth_handler)
60 def _http_error(self, error):
63 def _error(self, error):
64 raise APICallException(cause = error)
67 def publish_book(self, document):
68 yield {"text": document.text, "compressed": False}