Skip to content

Commit 26064d9

Browse files
Updated for 2.3
1 parent bd8f0d0 commit 26064d9

6 files changed

Lines changed: 29 additions & 85 deletions

File tree

snippets/models.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS])
1010
STYLE_CHOICES = sorted((item, item) for item in get_all_styles())
1111

12+
1213
class Snippet(models.Model):
1314
created = models.DateTimeField(auto_now_add=True)
1415
title = models.CharField(max_length=100, blank=True, default='')

snippets/permissions.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,12 @@
11
from rest_framework import permissions
22

3+
34
class IsOwnerOrReadOnly(permissions.BasePermission):
45
"""
56
Custom permission to only allow owners of an object to edit it.
67
"""
78

8-
def has_permission(self, request, view, obj=None):
9-
# Skip the check unless this is an object-level test
10-
if obj is None:
11-
return True
12-
9+
def has_object_permission(self, request, view, obj):
1310
# Read permissions are allowed to any request
1411
if request.method in permissions.SAFE_METHODS:
1512
return True

snippets/serializers.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
from snippets.models import Snippet
33
from django.contrib.auth.models import User
44

5+
56
class SnippetSerializer(serializers.HyperlinkedModelSerializer):
67
owner = serializers.Field(source='owner.username')
78
highlight = serializers.HyperlinkedIdentityField(view_name='snippet-highlight', format='html')

snippets/views.py

Lines changed: 17 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -1,98 +1,47 @@
11
from django.contrib.auth.models import User
2-
from rest_framework import generics
32
from rest_framework import permissions
43
from rest_framework import renderers
5-
from rest_framework.decorators import api_view
4+
from rest_framework import viewsets
5+
from rest_framework.decorators import link
66
from rest_framework.response import Response
7-
from rest_framework.reverse import reverse
87
from snippets.models import Snippet
98
from snippets.permissions import IsOwnerOrReadOnly
109
from snippets.serializers import SnippetSerializer, UserSerializer
1110

12-
@api_view(('GET',))
13-
def api_root(request, format=None):
14-
"""
15-
This is the entry point for the API described in the
16-
[REST framework tutorial][tutorial].
17-
18-
Follow the hyperinks each resource offers to explore the API.
19-
20-
Note that you can also explore the API from the command line, for instance
21-
using the `curl` command-line tool.
22-
23-
For example: `curl -X GET http://restframework.herokuapp.com/ -H "Accept: application/json; indent=4"`
2411

25-
[tutorial]: http://django-rest-framework.org/tutorial/1-serialization.html
12+
class SnippetViewSet(viewsets.ModelViewSet):
2613
"""
27-
return Response({
28-
'users': reverse('user-list', request=request, format=format),
29-
'snippets': reverse('snippet-list', request=request, format=format)
30-
})
31-
32-
33-
class SnippetList(generics.ListCreateAPIView):
34-
"""
35-
This view presents a list of code snippets, and allows new snippets to
36-
be created.
37-
38-
Try it yourself by logging in as one of these four users: **amy**, **max**,
39-
**jose** or **aziz** - The passwords are the same as the usernames.
40-
41-
Note that code snippets are paginated to a maximum of 10 per page,
42-
and the maximum number of code snippets is capped at 100 instances.
43-
"""
44-
model = Snippet
45-
serializer_class = SnippetSerializer
46-
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
47-
48-
def pre_save(self, obj):
49-
obj.owner = self.request.user
50-
51-
52-
class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
53-
"""
54-
This view presents an instance of a code snippet.
14+
This endpoint presents code snippets.
5515
5616
The `highlight` field presents a hyperlink to the hightlighted HTML
5717
representation of the code snippet.
5818
59-
The **owner** of the code snippet may update or delete this instance.
19+
The **owner** of the code snippet may update or delete instances
20+
of the code snippet.
6021
6122
Try it yourself by logging in as one of these four users: **amy**, **max**,
62-
**jose** or **aziz** - The passwords are the same as the usernames.
23+
**jose** or **aziz**. The passwords are the same as the usernames.
6324
"""
64-
model = Snippet
25+
queryset = Snippet.objects.all()
6526
serializer_class = SnippetSerializer
6627
permission_classes = (permissions.IsAuthenticatedOrReadOnly,
6728
IsOwnerOrReadOnly,)
6829

69-
def pre_save(self, obj):
70-
obj.owner = self.request.user
71-
72-
73-
class SnippetHighlight(generics.SingleObjectAPIView):
74-
model = Snippet
75-
renderer_classes = (renderers.StaticHTMLRenderer,)
76-
77-
def get(self, request, *args, **kwargs):
30+
@link(renderer_classes=(renderers.StaticHTMLRenderer,))
31+
def highlight(self, request, *args, **kwargs):
7832
snippet = self.get_object()
7933
return Response(snippet.highlighted)
8034

35+
def pre_save(self, obj):
36+
obj.owner = self.request.user
8137

82-
class UserList(generics.ListAPIView):
83-
"""
84-
This view presents a list of all the users in the system.
8538

86-
As you can see, related snippet instances are serialized using a
87-
hyperlinked representation.
39+
class UserViewSet(viewsets.ReadOnlyModelViewSet):
8840
"""
89-
model = User
90-
serializer_class = UserSerializer
91-
41+
This endpoint presents the users in the system.
9242
93-
class UserDetail(generics.RetrieveAPIView):
94-
"""
95-
This view presents a instance of one of the users in the system.
43+
As you can see, the collection of snippet instances owned by a user are
44+
serialized using a hyperlinked representation.
9645
"""
97-
model = User
46+
queryset = User.objects.all()
9847
serializer_class = UserSerializer

tutorial/settings.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111

1212
DATABASES = {
1313
'default': {
14-
'ENGINE': 'django.db.backends.sqlite3', # Or use an alternate database backend.
14+
'ENGINE': 'django.db.backends.sqlite3', # Or use an alternate database backend.
1515
'NAME': 'tmp.db', # Path to sqlite3 database file.
1616
'USER': '', # Not used with sqlite3.
1717
'PASSWORD': '', # Not used with sqlite3.
@@ -153,7 +153,7 @@
153153
}
154154

155155
REST_FRAMEWORK = {
156-
'PAGINATE_BY': 10
156+
'PAGINATE_BY': 10,
157157
}
158158

159159
import os

tutorial/urls.py

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,12 @@
11
from snippets import views
22
from django.conf.urls import patterns, url, include
3-
from rest_framework.urlpatterns import format_suffix_patterns
3+
from rest_framework.routers import DefaultRouter
44

5-
urlpatterns = format_suffix_patterns(patterns('snippets.views',
6-
url(r'^$', 'api_root'),
7-
url(r'^snippets/$', views.SnippetList.as_view(), name='snippet-list'),
8-
url(r'^snippets/(?P<pk>[0-9]+)/$', views.SnippetDetail.as_view(), name='snippet-detail'),
9-
url(r'^snippets/(?P<pk>[0-9]+)/highlight/$', views.SnippetHighlight.as_view(), name='snippet-highlight'),
10-
url(r'^users/$', views.UserList.as_view(), name='user-list'),
11-
url(r'^users/(?P<pk>[0-9]+)/$', views.UserDetail.as_view(), name='user-detail')
12-
))
5+
router = DefaultRouter()
6+
router.register(r'snippets', views.SnippetViewSet)
7+
router.register(r'users', views.UserViewSet)
138

14-
urlpatterns += patterns('',
9+
urlpatterns = patterns('',
10+
url(r'^', include(router.urls)),
1511
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
1612
)

0 commit comments

Comments
 (0)