Coding style overhaul for Python files (PEP8 conformant). Removed buggy csstidy pytho...
[redakcja.git] / lib / wlapi.py
1 # -*- coding: utf-8 -*-
2 #
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.
5 #
6 """
7    Abstraction over API for wolnelektury.pl
8 """
9 import urllib2
10 import functools
11 import django.utils.simplejson as json
12 import logging
13 logger = logging.getLogger("fnp.lib.wlapi")
14
15
16 class APICallException(Exception):
17     pass
18
19
20 def api_call(path, format="json"):
21     def wrapper(func):
22
23         @functools.wraps(func)
24         def wrapped(self, *args, **kwargs):
25             generator = func(self, *args, **kwargs)
26
27             data = generator.next()
28
29             # prepare request
30             rq = urllib2.Request(self.base_url + path + ".json")
31
32             # will send POST when there is data, GET otherwise
33             if data is not None:
34                 rq.add_data(json.dumps(data))
35                 rq.add_header("Content-Type", "application/json")
36
37             try:
38                 anwser = json.load(self.opener.open(rq))
39                 return generator.send(anwser)
40             except StopIteration:
41                 # by default, just return the anwser as a shorthand
42                 return anwser
43             except urllib2.HTTPError, error:
44                 return self._http_error(error)
45             except Exception, error:
46                 return self._error(error)
47         return wrapped
48
49     return wrapper
50
51
52 class WLAPI(object):
53
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']
58
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'])
63
64         self.opener = urllib2.build_opener(auth_handler)
65
66     def _http_error(self, error):
67         return self._error()
68
69     def _error(self, error):
70         raise APICallException(cause=error)
71
72     @api_call("books")
73     def publish_book(self, document):
74         yield {"text": document.text, "compressed": False}