Statistics
| Branch: | Tag: | Revision:

root / api / flavors.py @ aa197ee4

History | View | Annotate | Download (2.1 kB)

1
#
2
# Copyright (c) 2010 Greek Research and Technology Network
3
#
4

    
5
from django.conf.urls.defaults import patterns
6
from django.http import HttpResponse
7
from django.template.loader import render_to_string
8
from django.utils import simplejson as json
9

    
10
from synnefo.api.util import get_flavor, api_method
11
from synnefo.db.models import Flavor
12

    
13

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

    
20

    
21
def flavor_to_dict(flavor, detail=True):
22
    d = {'id': flavor.id, 'name': flavor.name}
23
    if detail:
24
        d['ram'] = flavor.ram
25
        d['disk'] = flavor.disk
26
        d['cpu'] = flavor.cpu
27
    return d
28

    
29

    
30
@api_method('GET')
31
def list_flavors(request, detail=False):
32
    # Normal Response Codes: 200, 203
33
    # Error Response Codes: computeFault (400, 500),
34
    #                       serviceUnavailable (503),
35
    #                       unauthorized (401),
36
    #                       badRequest (400),
37
    #                       overLimit (413)
38

    
39
    all_flavors = Flavor.objects.all()
40
    flavors = [flavor_to_dict(flavor, detail) for flavor in all_flavors]
41

    
42
    if request.serialization == 'xml':
43
        data = render_to_string('list_flavors.xml', {'flavors': flavors, 'detail': detail})
44
    else:
45
        data = json.dumps({'flavors': {'values': flavors}})
46

    
47
    return HttpResponse(data, status=200)
48

    
49
@api_method('GET')
50
def get_flavor_details(request, flavor_id):
51
    # Normal Response Codes: 200, 203
52
    # Error Response Codes: computeFault (400, 500),
53
    #                       serviceUnavailable (503),
54
    #                       unauthorized (401),
55
    #                       badRequest (400),
56
    #                       itemNotFound (404),
57
    #                       overLimit (413)
58

    
59
    flavor = get_flavor(flavor_id)
60
    flavordict = flavor_to_dict(flavor, detail=True)
61

    
62
    if request.serialization == 'xml':
63
        data = render_to_string('flavor.xml', {'flavor': flavordict})
64
    else:
65
        data = json.dumps({'flavor': flavordict})
66

    
67
    return HttpResponse(data, status=200)