DRF Tutorial
DRF Tutorial
Getting started
mkdir tut_drf2
python3 -m venv env
source env/bin/activate
pip install django
pip install djangorestframework
pip install pygments # We'll be using this for the code highlighting
django-admin startproject tut2
cd tut2
python manage.py startapp snippets
tutorial/settings.py
edit
INSTALLED_APPS = [
...
'rest_framework',
'snippets',
]
add
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10
}
python manage.py makemigrations snippets
python manage.py migrate snippets
snippets/model.py
from django.db import models
from pygments.lexers import get_all_lexers
from pygments.styles import get_all_styles
from pygments.lexers import get_lexer_by_name
from pygments.formatters.html import HtmlFormatter
from pygments import highlight
= [item for item in get_all_lexers() if item[1]]
LEXERS = sorted([(item[1][0], item[0]) for item in LEXERS])
LANGUAGE_CHOICES = sorted([(item, item) for item in get_all_styles()])
STYLE_CHOICES
class Snippet(models.Model):
= models.DateTimeField(auto_now_add=True)
created = models.CharField(max_length=100, blank=True, default='')
title = models.TextField()
code = models.BooleanField(default=False)
linenos = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100)
language = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100)
style = models.ForeignKey('auth.User', related_name='snippets', on_delete=models.CASCADE)
owner = models.TextField()
highlighted class Meta:
= ['created']
ordering
def save(self, *args, **kwargs):
"""
Use the `pygments` library to create a highlighted HTML
representation of the code snippet.
"""
= get_lexer_by_name(self.language)
lexer = 'table' if self.linenos else False
linenos = {'title': self.title} if self.title else {}
options = HtmlFormatter(style=self.style, linenos=linenos,
formatter =True, **options)
fullself.highlighted = highlight(self.code, lexer, formatter)
super().save(*args, **kwargs)
snippets/urls.py
from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from snippets import views
# API endpoints
= format_suffix_patterns([
urlpatterns '', views.api_root),
path('snippets/',
path(
views.SnippetList.as_view(),='snippet-list'),
name'snippets/<int:pk>/',
path(
views.SnippetDetail.as_view(),='snippet-detail'),
name'snippets/<int:pk>/highlight/',
path(
views.SnippetHighlight.as_view(),='snippet-highlight'),
name'users/',
path(
views.UserList.as_view(),='user-list'),
name'users/<int:pk>/',
path(
views.UserDetail.as_view(),='user-detail')
name ])
tut2/urls.py
from django.contrib import admin
from django.urls import path, include
= [
urlpatterns 'admin/', admin.site.urls),
path('', include('snippets.urls')),
path(
]
+= [
urlpatterns 'api-auth/', include('rest_framework.urls')),
path( ]
snippets/views.py
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
from rest_framework import generics
from rest_framework import permissions
from snippets.permissions import IsOwnerOrReadOnly
class SnippetList(generics.ListCreateAPIView):
= [permissions.IsAuthenticatedOrReadOnly,
permission_classes
IsOwnerOrReadOnly]= Snippet.objects.all()
queryset = SnippetSerializer
serializer_class def perform_create(self, serializer):
=self.request.user)
serializer.save(owner
class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
= [permissions.IsAuthenticatedOrReadOnly,
permission_classes
IsOwnerOrReadOnly]= Snippet.objects.all()
queryset = SnippetSerializer
serializer_class
from django.contrib.auth.models import User
from snippets.serializers import UserSerializer
class UserList(generics.ListAPIView):
= User.objects.all()
queryset = UserSerializer
serializer_class
class UserDetail(generics.RetrieveAPIView):
= User.objects.all()
queryset = UserSerializer
serializer_class
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.reverse import reverse
@api_view(['GET'])
def api_root(request, format=None):
return Response({
'users': reverse('user-list', request=request, format=format),
'snippets': reverse('snippet-list', request=request, format=format)
})
from rest_framework import renderers
class SnippetHighlight(generics.GenericAPIView):
= Snippet.objects.all()
queryset = [renderers.StaticHTMLRenderer]
renderer_classes
def get(self, request, *args, **kwargs):
= self.get_object()
snippet return Response(snippet.highlighted)
snippets/serializers.py
from rest_framework import serializers
from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES
from django.contrib.auth.models import User
class SnippetSerializer(serializers.HyperlinkedModelSerializer):
= serializers.ReadOnlyField(source='owner.username')
owner = serializers.HyperlinkedIdentityField(view_name='snippet-highlight', format='html')
highlight
class Meta:
= Snippet
model = ['url', 'id', 'highlight', 'owner',
fields 'title', 'code', 'linenos', 'language', 'style']
class UserSerializer(serializers.HyperlinkedModelSerializer):
= serializers.HyperlinkedRelatedField(many=True, view_name='snippet-detail', read_only=True)
snippets
class Meta:
= User
model = ['url', 'id', 'username', 'snippets'] fields
snippets/permissions.pyt
from rest_framework import permissions
class IsOwnerOrReadOnly(permissions.BasePermission):
"""
Custom permission to only allow owners of an object to edit it.
"""
def has_object_permission(self, request, view, obj):
# Read permissions are allowed to any request,
# so we'll always allow GET, HEAD or OPTIONS requests.
if request.method in permissions.SAFE_METHODS:
return True
# Write permissions are only allowed to the owner of the snippet.
return obj.owner == request.user