Exemple #1
0
def graphs(request, id):

    content_type = 'application/json'

    try:
        user_id = get_user_id_from_hatohol_server(request)
    except (NoHatoholUser, NoHatoholSession):
        return http.HttpResponseForbidden(content_type=content_type)

    if request.method == 'POST':
        graph = Graph(user_id=user_id, settings_json=request.body)
        try:
            graph.full_clean()
        except ValidationError as e:
            return http.HttpResponseBadRequest(json.dumps(e.messages),
                                               content_type=content_type)
        graph.save()
        response = http.HttpResponse(to_json(graph),
                                     content_type=content_type,
                                     status=201)
        response['Location'] = reverse('hatohol.views.graphs',
                                       args=[graph.id])
        return response
    elif request.method == 'PUT':
        if id is None:
            message = 'id is required'
            return http.HttpResponseBadRequest(to_json(message),
                                               content_type=content_type)
        try:
            graph = Graph.objects.get(id=id)
            if graph.user_id != user_id:
                return http.HttpResponseForbidden(content_type=content_type)
            graph.settings_json = request.body
            graph.full_clean()
            graph.save()
            return http.HttpResponse(to_json(graph),
                                     content_type=content_type)
        except Graph.DoesNotExist:
            return http.HttpResponseNotFound(content_type=content_type)
        except ValidationError as e:
            return http.HttpResponseBadRequest(json.dumps(e.messages),
                                               content_type=content_type)
    elif request.method == 'DELETE':
        if id is None:
            message = 'id is required'
            return http.HttpResponseBadRequest(to_json(message),
                                               content_type=content_type)
        try:
            graph = Graph.objects.get(id=id)
        except Graph.DoesNotExist:
            return http.HttpResponseNotFound()
        else:
            if graph.user_id != user_id:
                return http.HttpResponseForbidden(content_type=content_type)
            graph.delete()
            return http.HttpResponse()
    else:
        if id:
            try:
                graph = Graph.objects.get(id=id)
            except Graph.DoesNotExist:
                return http.HttpResponseNotFound()
            if graph.user_id != user_id:
                return http.HttpResponseForbidden(content_type=content_type)
            response = graph
        else:
            graphs = Graph.objects.filter(user_id=user_id).order_by('id')
            response = graphs
        return http.HttpResponse(to_json(response), content_type=content_type)