Statistics
| Branch: | Tag: | Revision:

root / api / flavors.py @ c36934a7

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

    
12

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

    
19

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

    
27

    
28
@api_method('GET')
29
def list_flavors(request, detail=False):
30
    # Normal Response Codes: 200, 203
31
    # Error Response Codes: computeFault (400, 500),
32
    #                       serviceUnavailable (503),
33
    #                       unauthorized (401),
34
    #                       badRequest (400),
35
    #                       overLimit (413)
36
    
37
    all_flavors = Flavor.objects.all()
38
    flavors = [flavor_to_dict(flavor, detail) for flavor in all_flavors]
39
    
40
    if request.type == 'xml':
41
        mimetype = 'application/xml'
42
        data = render_to_string('list_flavors.xml', {'flavors': flavors, 'detail': detail})
43
    else:
44
        mimetype = 'application/json'
45
        data = json.dumps({'flavors': {'values': flavors}})
46
    
47
    return HttpResponse(data, mimetype=mimetype, 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
    try:
60
        falvor_id = int(flavor_id)
61
        flavor = flavor_to_dict(Flavor.objects.get(id=flavor_id))
62
    except Flavor.DoesNotExist:
63
        raise ItemNotFound
64
    
65
    if request.type == 'xml':
66
        data = render_to_string('flavor.xml', {'flavor': flavor})
67
    else:
68
        data = json.dumps({'flavor': flavor})
69
    
70
    return HttpResponse(data, status=200)