flavors.py 2.26 KB
Newer Older
1
2
3
4
#
# Copyright (c) 2010 Greek Research and Technology Network
#

Giorgos Verigakis's avatar
Giorgos Verigakis committed
5
from django.conf.urls.defaults import patterns
6
7
from django.http import HttpResponse
from django.template.loader import render_to_string
8
from django.utils import simplejson as json
9

Giorgos Verigakis's avatar
Giorgos Verigakis committed
10
from synnefo.api.faults import ItemNotFound
Giorgos Verigakis's avatar
Giorgos Verigakis committed
11
12
13
from synnefo.api.util import get_user, get_request_dict, api_method
from synnefo.db.models import Flavor

14
15
16
17
18
19
20
21
22
23
24
25
26

urlpatterns = patterns('synnefo.api.flavors',
    (r'^(?:/|.json|.xml)?$', 'list_flavors'),
    (r'^/detail(?:.json|.xml)?$', 'list_flavors', {'detail': True}),
    (r'^/(\d+)(?:.json|.xml)?$', 'get_flavor_details'),
)


def flavor_to_dict(flavor, detail=True):
    d = {'id': flavor.id, 'name': flavor.name}
    if detail:
        d['ram'] = flavor.ram
        d['disk'] = flavor.disk
27
        d['cpu'] = flavor.cpu
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
    return d


@api_method('GET')
def list_flavors(request, detail=False):
    # Normal Response Codes: 200, 203
    # Error Response Codes: computeFault (400, 500),
    #                       serviceUnavailable (503),
    #                       unauthorized (401),
    #                       badRequest (400),
    #                       overLimit (413)
    
    all_flavors = Flavor.objects.all()
    flavors = [flavor_to_dict(flavor, detail) for flavor in all_flavors]
    
Giorgos Verigakis's avatar
Giorgos Verigakis committed
43
    if request.serialization == 'xml':
44
45
46
47
        data = render_to_string('list_flavors.xml', {'flavors': flavors, 'detail': detail})
    else:
        data = json.dumps({'flavors': {'values': flavors}})
    
Giorgos Verigakis's avatar
Giorgos Verigakis committed
48
    return HttpResponse(data, status=200)
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65

@api_method('GET')
def get_flavor_details(request, flavor_id):
    # Normal Response Codes: 200, 203
    # Error Response Codes: computeFault (400, 500),
    #                       serviceUnavailable (503),
    #                       unauthorized (401),
    #                       badRequest (400),
    #                       itemNotFound (404),
    #                       overLimit (413)

    try:
        falvor_id = int(flavor_id)
        flavor = flavor_to_dict(Flavor.objects.get(id=flavor_id))
    except Flavor.DoesNotExist:
        raise ItemNotFound
    
Giorgos Verigakis's avatar
Giorgos Verigakis committed
66
    if request.serialization == 'xml':
67
68
69
70
71
        data = render_to_string('flavor.xml', {'flavor': flavor})
    else:
        data = json.dumps({'flavor': flavor})
    
    return HttpResponse(data, status=200)