Example #1
0
def api(request, app, model, pk=None):
    """
        The main API view.
        A model (including app) must be specified.
        An instance can optionally be specified (by PK).
        If the instance is not specified, we operate on the model's 
        entire collection.
        Accepts GET, POST (for create and update) and DELETE requests.
        Returns in JSON format.
    """

    # Return a 404 if the model or instance doesn't exist
    model = get_model_or_404(app, model)
    obj = get_object_or_404(model, pk=pk) if pk else None

    # GET request - if an instance is specified return it,
    # otherwise return all model instances.
    if request.method == 'GET':
        return JsonResponse(obj or model)

    # POST request - if an instance is specified update it,
    # otherwise create a new one. Return the instance.
    elif request.method == 'POST':
        obj = obj or model()
        fields = [f.name for f in obj._meta.fields]
        for field in set(fields).intersection(set(request.POST)):
            setattr(obj, field, request.POST[field])
        obj.save()
        return JsonResponse(obj)

    # DELETE request - if an instance is specified delete it,
    # otherwise delete all the model instances. Return an emtpy response.
    elif request.method == 'DELETE':
        if obj:
            obj.delete()
        else:
            model.objects.all().delete()
        return JsonResponse()

    # Unrecognized request type, return a 404.
    else:
        raise Http404
Example #2
0
 def test_invalid_model(self):        
     with self.assertRaises(Http404):
         m = get_model_or_404('invalid', 'invalid')    
Example #3
0
 def test_valid_model(self):
     """A model object is returned for valid app and model names"""
     m = get_model_or_404('testapp', 'actor')
     self.assertEqual(m, Actor)