Revision c36934a7 api/util.py

b/api/util.py
27 27
    return name if sep else e.tag
28 28

  
29 29
def xml_to_dict(s):
30
    # XXX Quick and dirty
30 31
    def _xml_to_dict(e):
31 32
        root = {}
32 33
        d = root[tag_name(e)] = dict(e.items())
......
60 61
    return ''.join(choice(pool) for i in range(length))
61 62

  
62 63

  
63
def render_fault(fault, request):
64
def render_fault(request, fault):
64 65
    if settings.DEBUG or request.META.get('SERVER_NAME', None) == 'testserver':
65 66
        fault.details = format_exc(fault)
66 67
    if request.type == 'xml':
......
72 73
        data = json.dumps(d)
73 74
    return HttpResponse(data, mimetype=mimetype, status=fault.code)    
74 75

  
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
76
def api_method(http_method):
77
    def decorator(func):
78
        @wraps(func)
79
        def wrapper(request, *args, **kwargs):
80
            try:
81
                if request.path.endswith('.json'):
82
                    type = 'json'
83
                elif request.path.endswith('.xml'):
84
                    type = 'xml'
85
                elif request.META.get('HTTP_ACCEPT', None) == 'application/xml':
86
                    type = 'xml'
87
                else:
88
                    type = 'json'
89
                request.type = type
90
                
91
                if request.method != http_method:
92
                    raise BadRequest()
93
                
94
                resp = func(request, *args, **kwargs)
95
                resp['Content-Type'] = 'application/xml' if type == 'xml' else 'application/json'
96
                return resp
97
            except Fault, fault:
98
                return render_fault(request, fault)
99
            except Exception, e:
100
                log.exception('Unexpected error: %s' % e)
101
                fault = ServiceUnavailable()
102
                return render_fault(request, fault)
103
        return wrapper
104
    return decorator

Also available in: Unified diff