Statistics
| Branch: | Tag: | Revision:

root / api / util.py @ 7e2f9d4b

History | View | Annotate | Download (2.7 kB)

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

    
5
from synnefo.api.errors import *
6
from synnefo.db.models import *
7

    
8
from django.http import HttpResponse
9
from django.template.loader import render_to_string
10

    
11
from functools import wraps
12
from logging import getLogger
13
from random import choice
14
from string import ascii_letters, digits
15
from traceback import format_exc
16
from xml.etree import ElementTree
17
from xml.parsers.expat import ExpatError
18

    
19
import json
20

    
21

    
22
log = getLogger('synnefo.api')
23

    
24

    
25
def tag_name(e):
26
    ns, sep, name = e.tag.partition('}')
27
    return name if sep else e.tag
28

    
29
def xml_to_dict(s):
30
    def _xml_to_dict(e):
31
        root = {}
32
        d = root[tag_name(e)] = dict(e.items())
33
        for child in e.getchildren():
34
            d.update(_xml_to_dict(child))
35
        return root
36
    return _xml_to_dict(ElementTree.fromstring(s.strip()))
37

    
38
def get_user():
39
    # XXX Placeholder function, everything belongs to a single SynnefoUser for now
40
    try:
41
        return SynnefoUser.objects.all()[0]
42
    except IndexError:
43
        raise Unauthorized
44

    
45
def get_request_dict(request):
46
    data = request.raw_post_data
47
    if request.type == 'xml':
48
        try:
49
            return xml_to_dict(data)
50
        except ExpatError:
51
            raise BadRequest
52
    else:
53
        try:
54
            return json.loads(data)
55
        except ValueError:
56
            raise BadRequest
57

    
58
def random_password(length=8):
59
    pool = ascii_letters + digits
60
    return ''.join(choice(pool) for i in range(length))
61

    
62

    
63
def render_fault(fault, request):
64
    if settings.DEBUG or request.META.get('SERVER_NAME', None) == 'testserver':
65
        fault.details = format_exc(fault)
66
    if request.type == 'xml':
67
        mimetype = 'application/xml'
68
        data = render_to_string('fault.xml', dict(fault=fault))
69
    else:
70
        mimetype = 'application/json'
71
        d = {fault.name: {'code': fault.code, 'message': fault.message, 'details': fault.details}}
72
        data = json.dumps(d)
73
    return HttpResponse(data, mimetype=mimetype, status=fault.code)    
74

    
75
def api_method(func):
76
    @wraps(func)
77
    def wrapper(request, *args, **kwargs):
78
        try:
79
            if request.path.endswith('.json'):
80
                type = 'json'
81
            elif request.path.endswith('.xml'):
82
                type = 'xml'
83
            elif request.META.get('HTTP_ACCEPT', None) == 'application/xml':
84
                type = 'xml'
85
            else:
86
                type = 'json'
87
            request.type = type
88
            return func(request, *args, **kwargs)
89
        except Fault, fault:
90
            return render_fault(fault, request)
91
        except Exception, e:
92
            log.exception('Unexpected error: %s' % e)
93
            return HttpResponse(status=500)
94
    return wrapper