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")
16 class APICallException(Exception):
20 def api_call(path, format="json"):
23 @functools.wraps(func)
24 def wrapped(self, *args, **kwargs):
25 generator = func(self, *args, **kwargs)
27 data = generator.next()
30 rq = urllib2.Request(self.base_url + path + ".json")
32 # will send POST when there is data, GET otherwise
34 rq.add_data(json.dumps(data))
35 rq.add_header("Content-Type", "application/json")
38 anwser = json.load(self.opener.open(rq))
39 return generator.send(anwser)
41 # by default, just return the anwser as a shorthand
43 except urllib2.HTTPError, error:
44 return self._http_error(error)
45 except Exception, error:
46 return self._error(error)
54 def __init__(self, config_dict):
55 self.base_url = config_dict['URL']
56 self.auth_realm = config_dict['AUTH_REALM']
57 self.auth_user = config_dict['AUTH_USER']
59 auth_handler = urllib2.HTTPDigestAuthHandler()
60 auth_handler.add_password(
61 realm=self.auth_realm, uri=self.base_url,
62 user=self.auth_user, passwd=config_dict['AUTH_PASSWD'])
64 self.opener = urllib2.build_opener(auth_handler)
66 def _http_error(self, error):
69 def _error(self, error):
70 raise APICallException(cause=error)
73 def publish_book(self, document):
74 yield {"text": document.text, "compressed": False}