Statistics
| Branch: | Tag: | Revision:

root / api / flavors.py @ 29a59bc1

History | View | Annotate | Download (2.2 kB)

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

    
5
from synnefo.api.util import *
6
from synnefo.db.models import Flavor
7

    
8
from django.conf.urls.defaults import *
9
from django.http import HttpResponse
10
from django.template.loader import render_to_string
11
from django.utils import simplejson as json
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
    return d
27

    
28

    
29
@api_method('GET')
30
def list_flavors(request, detail=False):
31
    # Normal Response Codes: 200, 203
32
    # Error Response Codes: computeFault (400, 500),
33
    #                       serviceUnavailable (503),
34
    #                       unauthorized (401),
35
    #                       badRequest (400),
36
    #                       overLimit (413)
37
    
38
    all_flavors = Flavor.objects.all()
39
    flavors = [flavor_to_dict(flavor, detail) for flavor in all_flavors]
40
    
41
    if request.type == 'xml':
42
        mimetype = 'application/xml'
43
        data = render_to_string('list_flavors.xml', {'flavors': flavors, 'detail': detail})
44
    else:
45
        mimetype = 'application/json'
46
        data = json.dumps({'flavors': {'values': flavors}})
47
    
48
    return HttpResponse(data, mimetype=mimetype, status=200)
49

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

    
60
    try:
61
        falvor_id = int(flavor_id)
62
        flavor = flavor_to_dict(Flavor.objects.get(id=flavor_id))
63
    except Flavor.DoesNotExist:
64
        raise ItemNotFound
65
    
66
    if request.type == 'xml':
67
        data = render_to_string('flavor.xml', {'flavor': flavor})
68
    else:
69
        data = json.dumps({'flavor': flavor})
70
    
71
    return HttpResponse(data, status=200)