ソースを参照

Adding JSON response class and view for displaying all snippets in database

David Leonard 10 年 前
コミット
3cb34b412a
1 ファイル変更19 行追加0 行削除
  1. 19 0
      hackathon_starter/hackathon/views.py

+ 19 - 0
hackathon_starter/hackathon/views.py

@@ -132,3 +132,22 @@ def linkedin(request):
     context = {'title': 'linkedin Example','userdata': userinfo}
     return render(request, 'hackathon/linkedin.html', context)
 
+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)
+