root / astakosclient / astakosclient / __init__.py @ 25a04cdd
History | View | Annotate | Download (22.5 kB)
1 |
# Copyright (C) 2012, 2013 GRNET S.A. All rights reserved.
|
---|---|
2 |
#
|
3 |
# Redistribution and use in source and binary forms, with or
|
4 |
# without modification, are permitted provided that the following
|
5 |
# conditions are met:
|
6 |
#
|
7 |
# 1. Redistributions of source code must retain the above
|
8 |
# copyright notice, this list of conditions and the following
|
9 |
# disclaimer.
|
10 |
#
|
11 |
# 2. Redistributions in binary form must reproduce the above
|
12 |
# copyright notice, this list of conditions and the following
|
13 |
# disclaimer in the documentation and/or other materials
|
14 |
# provided with the distribution.
|
15 |
#
|
16 |
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
|
17 |
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
18 |
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
19 |
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
|
20 |
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
21 |
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
22 |
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
|
23 |
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
|
24 |
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
25 |
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
26 |
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
27 |
# POSSIBILITY OF SUCH DAMAGE.
|
28 |
#
|
29 |
# The views and conclusions contained in the software and
|
30 |
# documentation are those of the authors and should not be
|
31 |
# interpreted as representing official policies, either expressed
|
32 |
# or implied, of GRNET S.A.
|
33 |
|
34 |
import logging |
35 |
import urlparse |
36 |
import urllib |
37 |
import hashlib |
38 |
from copy import copy |
39 |
|
40 |
import simplejson |
41 |
from astakosclient.utils import \ |
42 |
retry, scheme_to_class, parse_request, check_input |
43 |
from astakosclient.errors import \ |
44 |
AstakosClientException, Unauthorized, BadRequest, NotFound, Forbidden, \ |
45 |
NoUserName, NoUUID, BadValue, QuotaLimit, InvalidResponse |
46 |
|
47 |
|
48 |
# --------------------------------------------------------------------
|
49 |
# Astakos API urls
|
50 |
API_AUTHENTICATE = "/astakos/api/authenticate"
|
51 |
API_USERCATALOGS = "/astakos/api/user_catalogs"
|
52 |
API_SERVICE_USERCATALOGS = "/astakos/api/service/user_catalogs"
|
53 |
API_GETSERVICES = "/astakos/api/get_services"
|
54 |
API_RESOURCES = "/astakos/api/resources"
|
55 |
API_QUOTAS = "/astakos/api/quotas"
|
56 |
API_SERVICE_QUOTAS = "/astakos/api/service_quotas"
|
57 |
API_COMMISSIONS = "/astakos/api/commissions"
|
58 |
API_COMMISSIONS_ACTION = API_COMMISSIONS + "/action"
|
59 |
API_FEEDBACK = "/astakos/api/feedback"
|
60 |
API_TOKENS = "/astakos/api/tokens"
|
61 |
TOKENS_ENDPOINTS = "endpoints"
|
62 |
|
63 |
|
64 |
# --------------------------------------------------------------------
|
65 |
# Astakos Client Class
|
66 |
|
67 |
def get_token_from_cookie(request, cookie_name): |
68 |
"""Extract token from the cookie name provided
|
69 |
|
70 |
Cookie should be in the same form as astakos
|
71 |
service sets its cookie contents:
|
72 |
<user_uniq>|<user_token>
|
73 |
|
74 |
"""
|
75 |
try:
|
76 |
cookie_content = urllib.unquote(request.COOKIE.get(cookie_name, None))
|
77 |
return cookie_content.split("|")[1] |
78 |
except:
|
79 |
return None |
80 |
|
81 |
|
82 |
class AstakosClient(): |
83 |
"""AstakosClient Class Implementation"""
|
84 |
|
85 |
# ----------------------------------
|
86 |
def __init__(self, astakos_url, retry=0, |
87 |
use_pool=False, pool_size=8, logger=None): |
88 |
"""Initialize AstakosClient Class
|
89 |
|
90 |
Keyword arguments:
|
91 |
astakos_url -- i.e https://accounts.example.com (string)
|
92 |
use_pool -- use objpool for http requests (boolean)
|
93 |
retry -- how many time to retry (integer)
|
94 |
logger -- pass a different logger
|
95 |
|
96 |
"""
|
97 |
if logger is None: |
98 |
logging.basicConfig( |
99 |
format='%(asctime)s [%(levelname)s] %(name)s %(message)s',
|
100 |
datefmt='%Y-%m-%d %H:%M:%S',
|
101 |
level=logging.INFO) |
102 |
logger = logging.getLogger("astakosclient")
|
103 |
logger.debug("Intialize AstakosClient: astakos_url = %s, "
|
104 |
"use_pool = %s" % (astakos_url, use_pool))
|
105 |
|
106 |
check_input("__init__", logger, astakos_url=astakos_url)
|
107 |
|
108 |
# Check for supported scheme
|
109 |
p = urlparse.urlparse(astakos_url) |
110 |
conn_class = scheme_to_class(p.scheme, use_pool, pool_size) |
111 |
if conn_class is None: |
112 |
m = "Unsupported scheme: %s" % p.scheme
|
113 |
logger.error(m) |
114 |
raise BadValue(m)
|
115 |
|
116 |
# Save astakos_url etc. in our class
|
117 |
self.retry = retry
|
118 |
self.logger = logger
|
119 |
self.netloc = p.netloc
|
120 |
self.scheme = p.scheme
|
121 |
self.path = p.path.rstrip('/') |
122 |
self.conn_class = conn_class
|
123 |
|
124 |
# ----------------------------------
|
125 |
@retry
|
126 |
def _call_astakos(self, token, request_path, headers=None, |
127 |
body=None, method="GET", log_body=True): |
128 |
"""Make the actual call to Astakos Service"""
|
129 |
if token is not None: |
130 |
hashed_token = hashlib.sha1() |
131 |
hashed_token.update(token) |
132 |
using_token = "using token %s" % (hashed_token.hexdigest())
|
133 |
else:
|
134 |
using_token = "without using token"
|
135 |
self.logger.debug(
|
136 |
"Make a %s request to %s %s with headers %s and body %s"
|
137 |
% (method, request_path, using_token, headers, |
138 |
body if log_body else "(not logged)")) |
139 |
|
140 |
# Check Input
|
141 |
if headers is None: |
142 |
headers = {} |
143 |
if body is None: |
144 |
body = {} |
145 |
path = self.path + "/" + request_path.strip('/') |
146 |
|
147 |
# Build request's header and body
|
148 |
kwargs = {} |
149 |
kwargs['headers'] = copy(headers)
|
150 |
if token is not None: |
151 |
kwargs['headers']['X-Auth-Token'] = token |
152 |
if body:
|
153 |
kwargs['body'] = copy(body)
|
154 |
kwargs['headers'].setdefault(
|
155 |
'content-type', 'application/octet-stream') |
156 |
kwargs['headers'].setdefault('content-length', |
157 |
len(body) if body else 0) |
158 |
|
159 |
try:
|
160 |
# Get the connection object
|
161 |
with self.conn_class(self.netloc) as conn: |
162 |
# Send request
|
163 |
(message, data, status) = \ |
164 |
_do_request(conn, method, path, **kwargs) |
165 |
except Exception as err: |
166 |
self.logger.error("Failed to send request: %s" % repr(err)) |
167 |
raise AstakosClientException(str(err)) |
168 |
|
169 |
# Return
|
170 |
self.logger.debug("Request returned with status %s" % status) |
171 |
if status == 400: |
172 |
raise BadRequest(message, data)
|
173 |
elif status == 401: |
174 |
raise Unauthorized(message, data)
|
175 |
elif status == 403: |
176 |
raise Forbidden(message, data)
|
177 |
elif status == 404: |
178 |
raise NotFound(message, data)
|
179 |
elif status < 200 or status >= 300: |
180 |
raise AstakosClientException(message, data, status)
|
181 |
|
182 |
try:
|
183 |
if data:
|
184 |
return simplejson.loads(unicode(data)) |
185 |
else:
|
186 |
return None |
187 |
except Exception as err: |
188 |
self.logger.error("Cannot parse response \"%s\" with simplejson: %s" |
189 |
% (data, str(err)))
|
190 |
raise InvalidResponse(str(err), data) |
191 |
|
192 |
# ------------------------
|
193 |
# do a GET to ``API_AUTHENTICATE``
|
194 |
def get_user_info(self, token, usage=False): |
195 |
"""Authenticate user and get user's info as a dictionary
|
196 |
|
197 |
Keyword arguments:
|
198 |
token -- user's token (string)
|
199 |
usage -- return usage information for user (boolean)
|
200 |
|
201 |
In case of success return user information (json parsed format).
|
202 |
Otherwise raise an AstakosClientException.
|
203 |
|
204 |
"""
|
205 |
# Send request
|
206 |
auth_path = copy(API_AUTHENTICATE) |
207 |
if usage:
|
208 |
auth_path += "?usage=1"
|
209 |
return self._call_astakos(token, auth_path) |
210 |
|
211 |
# ----------------------------------
|
212 |
# do a POST to ``API_USERCATALOGS`` (or ``API_SERVICE_USERCATALOGS``)
|
213 |
# with {'uuids': uuids}
|
214 |
def _uuid_catalog(self, token, uuids, req_path): |
215 |
req_headers = {'content-type': 'application/json'} |
216 |
req_body = parse_request({'uuids': uuids}, self.logger) |
217 |
data = self._call_astakos(
|
218 |
token, req_path, req_headers, req_body, "POST")
|
219 |
if "uuid_catalog" in data: |
220 |
return data.get("uuid_catalog") |
221 |
else:
|
222 |
m = "_uuid_catalog request returned %s. No uuid_catalog found" \
|
223 |
% data |
224 |
self.logger.error(m)
|
225 |
raise AstakosClientException(m)
|
226 |
|
227 |
def get_usernames(self, token, uuids): |
228 |
"""Return a uuid_catalog dictionary for the given uuids
|
229 |
|
230 |
Keyword arguments:
|
231 |
token -- user's token (string)
|
232 |
uuids -- list of user ids (list of strings)
|
233 |
|
234 |
The returned uuid_catalog is a dictionary with uuids as
|
235 |
keys and the corresponding user names as values
|
236 |
|
237 |
"""
|
238 |
req_path = copy(API_USERCATALOGS) |
239 |
return self._uuid_catalog(token, uuids, req_path) |
240 |
|
241 |
def get_username(self, token, uuid): |
242 |
"""Return the user name of a uuid (see get_usernames)"""
|
243 |
check_input("get_username", self.logger, uuid=uuid) |
244 |
uuid_dict = self.get_usernames(token, [uuid])
|
245 |
if uuid in uuid_dict: |
246 |
return uuid_dict.get(uuid)
|
247 |
else:
|
248 |
raise NoUserName(uuid)
|
249 |
|
250 |
def service_get_usernames(self, token, uuids): |
251 |
"""Return a uuid_catalog dict using a service's token"""
|
252 |
req_path = copy(API_SERVICE_USERCATALOGS) |
253 |
return self._uuid_catalog(token, uuids, req_path) |
254 |
|
255 |
def service_get_username(self, token, uuid): |
256 |
"""Return the displayName of a uuid using a service's token"""
|
257 |
check_input("service_get_username", self.logger, uuid=uuid) |
258 |
uuid_dict = self.service_get_usernames(token, [uuid])
|
259 |
if uuid in uuid_dict: |
260 |
return uuid_dict.get(uuid)
|
261 |
else:
|
262 |
raise NoUserName(uuid)
|
263 |
|
264 |
# ----------------------------------
|
265 |
# do a POST to ``API_USERCATALOGS`` (or ``API_SERVICE_USERCATALOGS``)
|
266 |
# with {'displaynames': display_names}
|
267 |
def _displayname_catalog(self, token, display_names, req_path): |
268 |
req_headers = {'content-type': 'application/json'} |
269 |
req_body = parse_request({'displaynames': display_names}, self.logger) |
270 |
data = self._call_astakos(
|
271 |
token, req_path, req_headers, req_body, "POST")
|
272 |
if "displayname_catalog" in data: |
273 |
return data.get("displayname_catalog") |
274 |
else:
|
275 |
m = "_displayname_catalog request returned %s. " \
|
276 |
"No displayname_catalog found" % data
|
277 |
self.logger.error(m)
|
278 |
raise AstakosClientException(m)
|
279 |
|
280 |
def get_uuids(self, token, display_names): |
281 |
"""Return a displayname_catalog for the given names
|
282 |
|
283 |
Keyword arguments:
|
284 |
token -- user's token (string)
|
285 |
display_names -- list of user names (list of strings)
|
286 |
|
287 |
The returned displayname_catalog is a dictionary with
|
288 |
the names as keys and the corresponding uuids as values
|
289 |
|
290 |
"""
|
291 |
req_path = copy(API_USERCATALOGS) |
292 |
return self._displayname_catalog(token, display_names, req_path) |
293 |
|
294 |
def get_uuid(self, token, display_name): |
295 |
"""Return the uuid of a name (see getUUIDs)"""
|
296 |
check_input("get_uuid", self.logger, display_name=display_name) |
297 |
name_dict = self.get_uuids(token, [display_name])
|
298 |
if display_name in name_dict: |
299 |
return name_dict.get(display_name)
|
300 |
else:
|
301 |
raise NoUUID(display_name)
|
302 |
|
303 |
def service_get_uuids(self, token, display_names): |
304 |
"""Return a display_name catalog using a service's token"""
|
305 |
req_path = copy(API_SERVICE_USERCATALOGS) |
306 |
return self._displayname_catalog(token, display_names, req_path) |
307 |
|
308 |
def service_get_uuid(self, token, display_name): |
309 |
"""Return the uuid of a name using a service's token"""
|
310 |
check_input("service_get_uuid", self.logger, display_name=display_name) |
311 |
name_dict = self.service_get_uuids(token, [display_name])
|
312 |
if display_name in name_dict: |
313 |
return name_dict.get(display_name)
|
314 |
else:
|
315 |
raise NoUUID(display_name)
|
316 |
|
317 |
# ----------------------------------
|
318 |
# do a GET to ``API_GETSERVICES``
|
319 |
def get_services(self): |
320 |
"""Return a list of dicts with the registered services"""
|
321 |
return self._call_astakos(None, copy(API_GETSERVICES)) |
322 |
|
323 |
# ----------------------------------
|
324 |
# do a GET to ``API_RESOURCES``
|
325 |
def get_resources(self): |
326 |
"""Return a dict of dicts with the available resources"""
|
327 |
return self._call_astakos(None, copy(API_RESOURCES)) |
328 |
|
329 |
# ----------------------------------
|
330 |
# do a POST to ``API_FEEDBACK``
|
331 |
def send_feedback(self, token, message, data): |
332 |
"""Send feedback to astakos service
|
333 |
|
334 |
keyword arguments:
|
335 |
token -- user's token (string)
|
336 |
message -- Feedback message
|
337 |
data -- Additional information about service client status
|
338 |
|
339 |
In case of success return nothing.
|
340 |
Otherwise raise an AstakosClientException
|
341 |
|
342 |
"""
|
343 |
check_input("send_feedback", self.logger, message=message, data=data) |
344 |
path = copy(API_FEEDBACK) |
345 |
req_body = urllib.urlencode( |
346 |
{'feedback_msg': message, 'feedback_data': data}) |
347 |
self._call_astakos(token, path, None, req_body, "POST") |
348 |
|
349 |
# ----------------------------------
|
350 |
# do a GET to ``API_TOKENS``/<user_token>/``TOKENS_ENDPOINTS``
|
351 |
def get_endpoints(self, token, belongs_to=None, marker=None, limit=None): |
352 |
"""Request registered endpoints from astakos
|
353 |
|
354 |
keyword arguments:
|
355 |
token -- user's token (string)
|
356 |
belongs_to -- user's uuid (string)
|
357 |
marker -- return endpoints whose ID is higher than marker's (int)
|
358 |
limit -- maximum number of endpoints to return (int)
|
359 |
|
360 |
Return a json formatted dictionary containing information
|
361 |
about registered endpoints.
|
362 |
|
363 |
WARNING: This api call encodes the user's token inside the url.
|
364 |
It's thoughs security unsafe to use it (both astakosclient and
|
365 |
nginx tend to log requested urls).
|
366 |
Avoid the use of get_endpoints method and use
|
367 |
get_user_info_with_endpoints instead.
|
368 |
|
369 |
"""
|
370 |
params = {} |
371 |
if belongs_to is not None: |
372 |
params['belongsTo'] = str(belongs_to) |
373 |
if marker is not None: |
374 |
params['marker'] = str(marker) |
375 |
if limit is not None: |
376 |
params['limit'] = str(limit) |
377 |
path = API_TOKENS + "/" + token + "/" + \ |
378 |
TOKENS_ENDPOINTS + "?" + urllib.urlencode(params)
|
379 |
return self._call_astakos(token, path) |
380 |
|
381 |
# ----------------------------------
|
382 |
# do a POST to ``API_TOKENS``
|
383 |
def get_user_info_with_endpoints(self, token, uuid=None): |
384 |
""" Fallback call for authenticate
|
385 |
|
386 |
Keyword arguments:
|
387 |
token -- user's token (string)
|
388 |
uuid -- user's uniq id
|
389 |
|
390 |
It returns back the token as well as information about the token
|
391 |
holder and the services he/she can acess (in json format).
|
392 |
In case of error raise an AstakosClientException.
|
393 |
|
394 |
"""
|
395 |
req_path = copy(API_TOKENS) |
396 |
req_headers = {'content-type': 'application/json'} |
397 |
body = {'auth': {'token': {'id': token}}} |
398 |
if uuid is not None: |
399 |
body['auth']['tenantName'] = uuid |
400 |
req_body = parse_request(body, self.logger)
|
401 |
return self._call_astakos(token, req_path, req_headers, |
402 |
req_body, "POST", False) |
403 |
|
404 |
# ----------------------------------
|
405 |
# do a GET to ``API_QUOTAS``
|
406 |
def get_quotas(self, token): |
407 |
"""Get user's quotas
|
408 |
|
409 |
Keyword arguments:
|
410 |
token -- user's token (string)
|
411 |
|
412 |
In case of success return a dict of dicts with user's current quotas.
|
413 |
Otherwise raise an AstakosClientException
|
414 |
|
415 |
"""
|
416 |
return self._call_astakos(token, copy(API_QUOTAS)) |
417 |
|
418 |
# ----------------------------------
|
419 |
# do a GET to ``API_SERVICE_QUOTAS``
|
420 |
def service_get_quotas(self, token, user=None): |
421 |
"""Get all quotas for resources associated with the service
|
422 |
|
423 |
Keyword arguments:
|
424 |
token -- service's token (string)
|
425 |
user -- optionally, the uuid of a specific user
|
426 |
|
427 |
In case of success return a dict of dicts of dicts with current quotas
|
428 |
for all users, or of a specified user, if user argument is set.
|
429 |
Otherwise raise an AstakosClientException
|
430 |
|
431 |
"""
|
432 |
query = copy(API_SERVICE_QUOTAS) |
433 |
if user is not None: |
434 |
query += "?user=" + user
|
435 |
return self._call_astakos(token, query) |
436 |
|
437 |
# ----------------------------------
|
438 |
# do a POST to ``API_COMMISSIONS``
|
439 |
def issue_commission(self, token, request): |
440 |
"""Issue a commission
|
441 |
|
442 |
Keyword arguments:
|
443 |
token -- service's token (string)
|
444 |
request -- commision request (dict)
|
445 |
|
446 |
In case of success return commission's id (int).
|
447 |
Otherwise raise an AstakosClientException.
|
448 |
|
449 |
"""
|
450 |
req_headers = {'content-type': 'application/json'} |
451 |
req_body = parse_request(request, self.logger)
|
452 |
try:
|
453 |
response = self._call_astakos(token, copy(API_COMMISSIONS),
|
454 |
req_headers, req_body, "POST")
|
455 |
except AstakosClientException as err: |
456 |
if err.status == 413: |
457 |
raise QuotaLimit(err.message, err.details)
|
458 |
else:
|
459 |
raise
|
460 |
|
461 |
if "serial" in response: |
462 |
return response['serial'] |
463 |
else:
|
464 |
m = "issue_commission_core request returned %s. No serial found" \
|
465 |
% response |
466 |
self.logger.error(m)
|
467 |
raise AstakosClientException(m)
|
468 |
|
469 |
def issue_one_commission(self, token, holder, source, provisions, |
470 |
name="", force=False, auto_accept=False): |
471 |
"""Issue one commission (with specific holder and source)
|
472 |
|
473 |
keyword arguments:
|
474 |
token -- service's token (string)
|
475 |
holder -- user's id (string)
|
476 |
source -- commission's source (ex system) (string)
|
477 |
provisions -- resources with their quantity (dict from string to int)
|
478 |
name -- description of the commission (string)
|
479 |
force -- force this commission (boolean)
|
480 |
auto_accept -- auto accept this commission (boolean)
|
481 |
|
482 |
In case of success return commission's id (int).
|
483 |
Otherwise raise an AstakosClientException.
|
484 |
(See also issue_commission)
|
485 |
|
486 |
"""
|
487 |
check_input("issue_one_commission", self.logger, |
488 |
holder=holder, source=source, |
489 |
provisions=provisions) |
490 |
|
491 |
request = {} |
492 |
request["force"] = force
|
493 |
request["auto_accept"] = auto_accept
|
494 |
request["name"] = name
|
495 |
try:
|
496 |
request["provisions"] = []
|
497 |
for resource, quantity in provisions.iteritems(): |
498 |
t = {"holder": holder, "source": source, |
499 |
"resource": resource, "quantity": quantity} |
500 |
request["provisions"].append(t)
|
501 |
except Exception as err: |
502 |
self.logger.error(str(err)) |
503 |
raise BadValue(str(err)) |
504 |
|
505 |
return self.issue_commission(token, request) |
506 |
|
507 |
# ----------------------------------
|
508 |
# do a GET to ``API_COMMISSIONS``
|
509 |
def get_pending_commissions(self, token): |
510 |
"""Get Pending Commissions
|
511 |
|
512 |
Keyword arguments:
|
513 |
token -- service's token (string)
|
514 |
|
515 |
In case of success return a list of pending commissions' ids
|
516 |
(list of integers)
|
517 |
|
518 |
"""
|
519 |
return self._call_astakos(token, copy(API_COMMISSIONS)) |
520 |
|
521 |
# ----------------------------------
|
522 |
# do a GET to ``API_COMMISSIONS``/<serial>
|
523 |
def get_commission_info(self, token, serial): |
524 |
"""Get Description of a Commission
|
525 |
|
526 |
Keyword arguments:
|
527 |
token -- service's token (string)
|
528 |
serial -- commission's id (int)
|
529 |
|
530 |
In case of success return a dict of dicts containing
|
531 |
informations (details) about the requested commission
|
532 |
|
533 |
"""
|
534 |
check_input("get_commission_info", self.logger, serial=serial) |
535 |
|
536 |
path = API_COMMISSIONS + "/" + str(serial) |
537 |
return self._call_astakos(token, path) |
538 |
|
539 |
# ----------------------------------
|
540 |
# do a POST to ``API_COMMISSIONS``/<serial>/action"
|
541 |
def commission_action(self, token, serial, action): |
542 |
"""Perform a commission action
|
543 |
|
544 |
Keyword arguments:
|
545 |
token -- service's token (string)
|
546 |
serial -- commission's id (int)
|
547 |
action -- action to perform, currently accept/reject (string)
|
548 |
|
549 |
In case of success return nothing.
|
550 |
|
551 |
"""
|
552 |
check_input("commission_action", self.logger, |
553 |
serial=serial, action=action) |
554 |
|
555 |
path = API_COMMISSIONS + "/" + str(serial) + "/action" |
556 |
req_headers = {'content-type': 'application/json'} |
557 |
req_body = parse_request({str(action): ""}, self.logger) |
558 |
self._call_astakos(token, path, req_headers, req_body, "POST") |
559 |
|
560 |
def accept_commission(self, token, serial): |
561 |
"""Accept a commission (see commission_action)"""
|
562 |
self.commission_action(token, serial, "accept") |
563 |
|
564 |
def reject_commission(self, token, serial): |
565 |
"""Reject a commission (see commission_action)"""
|
566 |
self.commission_action(token, serial, "reject") |
567 |
|
568 |
# ----------------------------------
|
569 |
# do a POST to ``API_COMMISSIONS_ACTION``
|
570 |
def resolve_commissions(self, token, accept_serials, reject_serials): |
571 |
"""Resolve multiple commissions at once
|
572 |
|
573 |
Keyword arguments:
|
574 |
token -- service's token (string)
|
575 |
accept_serials -- commissions to accept (list of ints)
|
576 |
reject_serials -- commissions to reject (list of ints)
|
577 |
|
578 |
In case of success return a dict of dicts describing which
|
579 |
commissions accepted, which rejected and which failed to
|
580 |
resolved.
|
581 |
|
582 |
"""
|
583 |
check_input("resolve_commissions", self.logger, |
584 |
accept_serials=accept_serials, |
585 |
reject_serials=reject_serials) |
586 |
|
587 |
path = copy(API_COMMISSIONS_ACTION) |
588 |
req_headers = {'content-type': 'application/json'} |
589 |
req_body = parse_request({"accept": accept_serials,
|
590 |
"reject": reject_serials},
|
591 |
self.logger)
|
592 |
return self._call_astakos(token, path, req_headers, req_body, "POST") |
593 |
|
594 |
|
595 |
# --------------------------------------------------------------------
|
596 |
# Private functions
|
597 |
# We want _doRequest to be a distinct function
|
598 |
# so that we can replace it during unit tests.
|
599 |
def _do_request(conn, method, url, **kwargs): |
600 |
"""The actual request. This function can easily be mocked"""
|
601 |
conn.request(method, url, **kwargs) |
602 |
response = conn.getresponse() |
603 |
length = response.getheader('content-length', None) |
604 |
data = response.read(length) |
605 |
status = int(response.status)
|
606 |
message = response.reason |
607 |
return (message, data, status)
|