root / api / helpers.py @ b016b476
History | View | Annotate | Download (1.8 kB)
1 |
# vim: ts=4 sts=4 et ai sw=4 fileencoding=utf-8
|
---|---|
2 |
#
|
3 |
# Copyright © 2010 Greek Research and Technology Network
|
4 |
#
|
5 |
|
6 |
# XXX: most of the keys below are dummy
|
7 |
def instance_to_server(instance): |
8 |
server = { |
9 |
"id": instance["name"], |
10 |
"name": instance["name"], |
11 |
"hostId": instance["pnode"], |
12 |
"imageRef": 1, |
13 |
"flavorRef": 1, |
14 |
"addresses": {
|
15 |
"public": [ ],
|
16 |
"private": [ ],
|
17 |
}, |
18 |
"metadata": { }
|
19 |
} |
20 |
if instance["status"] == "running": |
21 |
server["status"] = "ACTIVE" |
22 |
elif instance["status"] == "ADMIN_down": |
23 |
server["status"] = "SUSPENDED" |
24 |
else:
|
25 |
server["status"] = "UNKNOWN" |
26 |
|
27 |
return server
|
28 |
|
29 |
|
30 |
def paginator(func): |
31 |
"""
|
32 |
A dummy paginator decorator that uses limit/offset query parameters to
|
33 |
limit the result set of a view. The view must return a dict with a single
|
34 |
key and an iterable for its value.
|
35 |
|
36 |
This doesn't actually speed up the internal processing, but it's useful to
|
37 |
easily provide compatibility for the API
|
38 |
"""
|
39 |
def inner_func(self, request, *args, **kwargs): |
40 |
resp = func(self, request, *args, **kwargs)
|
41 |
if 'limit' not in request.GET or 'offset' not in request.GET: |
42 |
return resp
|
43 |
|
44 |
# handle structures such as { '
|
45 |
if len(resp.keys()) != 1: |
46 |
return resp
|
47 |
key = resp.keys()[0]
|
48 |
full = resp.values()[0]
|
49 |
|
50 |
try:
|
51 |
limit = int(request.GET['limit']) |
52 |
offset = int(request.GET['offset']) |
53 |
if offset < 0: |
54 |
raise ValueError |
55 |
if limit < 0: |
56 |
raise ValueError |
57 |
limit = limit + offset |
58 |
partial = full[offset:limit] |
59 |
return { key: partial }
|
60 |
except (ValueError, TypeError): |
61 |
return { key: [] }
|
62 |
|
63 |
return inner_func
|