forked from giacbrd/python-dandelion-eu
-
Notifications
You must be signed in to change notification settings - Fork 0
/
base.py
107 lines (85 loc) · 3.48 KB
/
base.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
""" base classes
"""
from __future__ import unicode_literals
try:
import urlparse
except ImportError:
from urllib import parse as urlparse
from dandelion.cache.base import NoCache
from dandelion.utils import AttributeDict
class DandelionConfig(dict):
""" class for storing the default dandelion configuration, such
as authentication parameters
"""
ALLOWED_KEYS = ['token', 'model']
def __setitem__(self, key, value):
if not key in self.ALLOWED_KEYS:
raise DandelionException('invalid config param: {}'.format(key))
super(DandelionConfig, self).__setitem__(key, value)
class DandelionException(BaseException):
error = True
def __init__(self, dandelion_obj=None, **kwargs):
if isinstance(dandelion_obj, AttributeDict):
self.message = dandelion_obj.message
self.code = dandelion_obj.code
self.data = dandelion_obj.data
else:
self.message = "{}".format(dandelion_obj)
self.code = kwargs.get('code')
self.data = kwargs.get('data')
super(DandelionException, self).__init__(self.message)
class MissingParameterException(DandelionException):
code = 'error.missingParameter'
def __init__(self, param_name):
self.data = {'parameter': param_name}
super(MissingParameterException, self).__init__(
'Param "{}" is required'.format(param_name)
)
class BaseDandelionRequest(object):
DANDELION_HOST = 'api.dandelion.eu'
REQUIRE_AUTH = True
def __init__(self, **kwargs):
import requests
from dandelion import default_config
self.uri = self._get_uri(host=kwargs.get('host'))
self.token = kwargs.get('token', default_config.get('token'))
self.model = kwargs.get('model', default_config.get('model'))
self.requests = requests.session()
self.cache = kwargs.get('cache', NoCache())
if self.REQUIRE_AUTH and not self.token:
raise MissingParameterException("token")
def do_request(self, params, extra_url='', method='post', **kwargs):
if self.REQUIRE_AUTH:
params['token'] = self.token
url = self.uri + ''.join('/' + x for x in extra_url)
cache_key = self.cache.get_key_for(
url=url, params=params, method=method
)
if self.cache.contains_key(cache_key):
response = self.cache.get(cache_key)
else:
response = self._do_raw_request(url, params, method, **kwargs)
if response.ok:
self.cache.set(cache_key, response)
obj = response.json(object_hook=AttributeDict)
if not response.ok:
raise DandelionException(obj)
return obj
def _get_uri(self, host=None):
base_uri = host or self.DANDELION_HOST
if not base_uri.startswith('http'):
base_uri = 'https://' + base_uri
return urlparse.urljoin(
base_uri, '/'.join(self._get_uri_tokens())
)
def _do_raw_request(self, url, params, method, **kwargs):
from dandelion import __version__
kwargs['data' if method in ('post', 'put') else 'params'] = params
kwargs['url'] = url
kwargs['headers'] = kwargs.pop('headers', {})
kwargs['headers']['User-Agent'] = kwargs['headers'].get(
'User-Agent', 'python-dandelion-eu/' + __version__
)
return getattr(self.requests, method)(**kwargs)
def _get_uri_tokens(self):
raise NotImplementedError