瀏覽代碼

replace function based view with class based view

We now define a base class, CRUDBaseView which provides
all the typical CRUD operations. I imagine using the mixins
is the most flexible / fast way to get things done hackathon
style. So I went for that. You can pull a mixin out, or override
as you please.
Luke Murphy 10 年之前
父節點
當前提交
eec9f41159
共有 1 個文件被更改,包括 14 次插入20 次删除
  1. 14 20
      hackathon_starter/hackathon/views.py

+ 14 - 20
hackathon_starter/hackathon/views.py

@@ -11,6 +11,9 @@ from django.contrib.auth.decorators import login_required
 from django.views.decorators.csrf import csrf_exempt
 from django.views.decorators.csrf import csrf_exempt
 from django.http import JsonResponse
 from django.http import JsonResponse
 
 
+# Django REST Framework
+from rest_framework import viewsets, mixins
+
 import requests
 import requests
 import pdb
 import pdb
 
 
@@ -35,8 +38,6 @@ from scripts.foursquare import *
 # Python
 # Python
 import oauth2 as oauth
 import oauth2 as oauth
 import simplejson as json
 import simplejson as json
-from rest_framework.renderers import JSONRenderer
-from rest_framework.parsers import JSONParser
 
 
 # Models
 # Models
 from hackathon.models import Snippet, Profile, InstagramProfile, TwitterProfile, MeetupToken, GithubProfile, LinkedinProfile, FacebookProfile, TumblrProfile, GoogleProfile, DropboxProfile, FoursquareProfile
 from hackathon.models import Snippet, Profile, InstagramProfile, TwitterProfile, MeetupToken, GithubProfile, LinkedinProfile, FacebookProfile, TumblrProfile, GoogleProfile, DropboxProfile, FoursquareProfile
@@ -707,24 +708,17 @@ def linkedin(request):
 # Snippet RESTful Model #
 # Snippet RESTful Model #
 #########################
 #########################
 
 
-class JSONResponse(HttpResponse):
-    """
-    An HttpResponse that renders its content into JSON.
-    """
-    def __init__(self, data, **kwargs):
-        content = JSONRenderer().render(data)
-        kwargs['content_type'] = 'application/json'
-        super(JSONResponse, self).__init__(content, **kwargs)
-
-@csrf_exempt
-def snippet_list(request):
-    """
-    List all code snippets, or create a new snippet.
-    """
-    if request.method == 'GET':
-        snippets = Snippet.objects.all()
-        serializer = SnippetSerializer(snippets, many=True)
-        return JSONResponse(serializer.data)
+class CRUDBaseView(mixins.ListModelMixin,
+                  mixins.CreateModelMixin,
+                  mixins.RetrieveModelMixin,
+                  mixins.UpdateModelMixin,
+                  mixins.DestroyModelMixin,
+                  viewsets.GenericViewSet):
+    pass
+
+class SnippetView(CRUDBaseView):
+    serializer_class = SnippetSerializer
+    queryset = Snippet.objects.all()
 
 
 
 
 ##################
 ##################