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
11 import django.utils.simplejson as json
13 logger = logging.getLogger("fnp.lib.wlapi")
15 class APICallException(Exception):
18 def api_call(path, format="json"):
21 @functools.wraps(func)
22 def wrapped(self, *args, **kwargs):
23 generator = func(self, *args, **kwargs)
25 data = generator.next()
28 rq = urllib2.Request(self.base_url + path + ".json")
30 # will send POST when there is data, GET otherwise
32 rq.add_data(json.dumps(data))
33 rq.add_header("Content-Type", "application/json")
36 anwser = json.load(self.opener.open(rq))
37 return generator.send(anwser)
39 # by default, just return the anwser as a shorthand
41 except urllib2.HTTPError, error:
42 return self._http_error(error)
43 except Exception, error:
44 return self._error(error)
53 def __init__(self, config_dict):
54 self.base_url = config_dict['URL']
55 self.auth_realm = config_dict['AUTH_REALM']
56 self.auth_user = config_dict['AUTH_USER']
58 auth_handler = urllib2.HTTPDigestAuthHandler();
59 auth_handler.add_password(
60 realm=self.auth_realm, uri=self.base_url,
61 user=self.auth_user, passwd=config_dict['AUTH_PASSWD'])
63 self.opener = urllib2.build_opener(auth_handler)
65 def _http_error(self, error):
68 def _error(self, error):
69 raise APICallException(cause = error)
72 def publish_book(self, document):
73 yield {"text": document.text, "compressed": False}