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