Debian Codegraph @

docs/tutorial/3-class-based-views.md

raw
1 # Tutorial 3: Class-based Views
2
3 We can also write our API views using class-based views, rather than function based views. As we'll see this is a powerful pattern that allows us to reuse common functionality, and helps us keep our code [DRY][dry].
4
5 ## Rewriting our API using class-based views
6
7 We'll start by rewriting the root view as a class-based view. All this involves is a little bit of refactoring of `views.py`.
8
9 ```python
10 from snippets.models import Snippet
11 from snippets.serializers import SnippetSerializer
12 from django.http import Http404
13 from rest_framework.views import APIView
14 from rest_framework.response import Response
15 from rest_framework import status
16
17
18 class SnippetList(APIView):
19 """
20 List all snippets, or create a new snippet.
21 """
22
23 def get(self, request, format=None):
24 snippets = Snippet.objects.all()
25 serializer = SnippetSerializer(snippets, many=True)
26 return Response(serializer.data)
27
28 def post(self, request, format=None):
29 serializer = SnippetSerializer(data=request.data)
30 if serializer.is_valid():
31 serializer.save()
32 return Response(serializer.data, status=status.HTTP_201_CREATED)
33 return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
34 ```
35
36 So far, so good. It looks pretty similar to the previous case, but we've got better separation between the different HTTP methods. We'll also need to update the instance view in `views.py`.
37
38 ```python
39 class SnippetDetail(APIView):
40 """
41 Retrieve, update or delete a snippet instance.
42 """
43
44 def get_object(self, pk):
45 try:
46 return Snippet.objects.get(pk=pk)
47 except Snippet.DoesNotExist:
48 raise Http404
49
50 def get(self, request, pk, format=None):
51 snippet = self.get_object(pk)
52 serializer = SnippetSerializer(snippet)
53 return Response(serializer.data)
54
55 def put(self, request, pk, format=None):
56 snippet = self.get_object(pk)
57 serializer = SnippetSerializer(snippet, data=request.data)
58 if serializer.is_valid():
59 serializer.save()
60 return Response(serializer.data)
61 return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
62
63 def delete(self, request, pk, format=None):
64 snippet = self.get_object(pk)
65 snippet.delete()
66 return Response(status=status.HTTP_204_NO_CONTENT)
67 ```
68
69 That's looking good. Again, it's still pretty similar to the function based view right now.
70
71 We'll also need to refactor our `snippets/urls.py` slightly now that we're using class-based views.
72
73 ```python
74 from django.urls import path
75 from rest_framework.urlpatterns import format_suffix_patterns
76 from snippets import views
77
78 urlpatterns = [
79 path("snippets/", views.SnippetList.as_view()),
80 path("snippets/<int:pk>/", views.SnippetDetail.as_view()),
81 ]
82
83 urlpatterns = format_suffix_patterns(urlpatterns)
84 ```
85
86 Okay, we're done. If you run the development server everything should be working just as before.
87
88 ## Using mixins
89
90 One of the big wins of using class-based views is that it allows us to easily compose reusable bits of behavior.
91
92 The create/retrieve/update/delete operations that we've been using so far are going to be pretty similar for any model-backed API views we create. Those bits of common behavior are implemented in REST framework's mixin classes.
93
94 Let's take a look at how we can compose the views by using the mixin classes. Here's our `views.py` module again.
95
96 ```python
97 from snippets.models import Snippet
98 from snippets.serializers import SnippetSerializer
99 from rest_framework import mixins
100 from rest_framework import generics
101
102
103 class SnippetList(
104 mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView
105 ):
106 queryset = Snippet.objects.all()
107 serializer_class = SnippetSerializer
108
109 def get(self, request, *args, **kwargs):
110 return self.list(request, *args, **kwargs)
111
112 def post(self, request, *args, **kwargs):
113 return self.create(request, *args, **kwargs)
114 ```
115
116 We'll take a moment to examine exactly what's happening here. We're building our view using `GenericAPIView`, and adding in `ListModelMixin` and `CreateModelMixin`.
117
118 The base class provides the core functionality, and the mixin classes provide the `.list()` and `.create()` actions. We're then explicitly binding the `get` and `post` methods to the appropriate actions. Simple enough stuff so far.
119
120 ```python
121 class SnippetDetail(
122 mixins.RetrieveModelMixin,
123 mixins.UpdateModelMixin,
124 mixins.DestroyModelMixin,
125 generics.GenericAPIView,
126 ):
127 queryset = Snippet.objects.all()
128 serializer_class = SnippetSerializer
129
130 def get(self, request, *args, **kwargs):
131 return self.retrieve(request, *args, **kwargs)
132
133 def put(self, request, *args, **kwargs):
134 return self.update(request, *args, **kwargs)
135
136 def delete(self, request, *args, **kwargs):
137 return self.destroy(request, *args, **kwargs)
138 ```
139
140 Pretty similar. Again we're using the `GenericAPIView` class to provide the core functionality, and adding in mixins to provide the `.retrieve()`, `.update()` and `.destroy()` actions.
141
142 ## Using generic class-based views
143
144 Using the mixin classes we've rewritten the views to use slightly less code than before, but we can go one step further. REST framework provides a set of already mixed-in generic views that we can use to trim down our `views.py` module even more.
145
146 ```python
147 from snippets.models import Snippet
148 from snippets.serializers import SnippetSerializer
149 from rest_framework import generics
150
151
152 class SnippetList(generics.ListCreateAPIView):
153 queryset = Snippet.objects.all()
154 serializer_class = SnippetSerializer
155
156
157 class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
158 queryset = Snippet.objects.all()
159 serializer_class = SnippetSerializer
160 ```
161
162 Wow, that's pretty concise. We've gotten a huge amount for free, and our code looks like good, clean, idiomatic Django.
163
164 Next we'll move onto [part 4 of the tutorial][tut-4], where we'll take a look at how we can deal with authentication and permissions for our API.
165
166 [dry]: https://en.wikipedia.org/wiki/Don't_repeat_yourself
167 [tut-4]: 4-authentication-and-permissions.md