Give your Django a REST



Give your Django a REST

1 0


DjangoRestFrameworkTalk

A Talk on the Django Rest Framework

On Github kitanata / DjangoRestFrameworkTalk

Give your Django a REST

An Introduction to the Django-REST-Framework

By Raymond Chandler III / @raymondchandler

Step 1. Create the model

from django.db import models

class Talk(models.Model):
    updated_at = models.DateTimeField(auto_now=True)
    created_at = models.DateTimeField(auto_now_add=True)

    name = models.CharField(max_length=140)
    abstract = models.CharField(max_length=4000)

    published = models.BooleanField(default=True)

    def __unicode__(self):
        return unicode(self.name)

    def get_absolute_url(self):
        return "/talk/" + str(self.pk)

Step 2. Write the serializer

from rest_framework import serializers
from talks.models import Talk

class TalkSerializer(serializers.ModelSerializer):
    class Meta:
        model = Talk
        fields = (
                'id', 
                'name', 
                'created_at',
                'updated_at',
                'abstract', 
                'published')

Step 3. Write the view.

from rest_framework import generics, permissions, viewsets
from talks.models import Talk
from talks.serializers import TalkSerializer

class TalkDetail(viewsets.ModelViewSet):
    queryset = Talk.objects.all()
    serializer_class = TalkSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)

Step 4. Configure the URL.

url(r'^rest/talk/(?P<pk>\d*)$', TalkDetail.as_view())

Step 5. ...

Step 6. PROFIT!

{
    "id": 1, 
    "created_at": "2013-09-11T21:12:15.868", 
    "updated_at": "2013-09-13T19:23:00.789", 
    "name": "Saving The MAFIAA: What I learned on Cherry Blossom Ave.", 
    "abstract": "Zombie ipsum reversus ab viral inferno, nam rick grimes malum cerebro. De carne lumbering animata corpora quaeritis. Summus brains sit morbo vel maleficia? De apocalypsi gorger omero undead survivor dictum mauris. Hi mindless mortuis soulless creaturas, imo evil stalking monstra adventus resi dentevil vultus comedat cerebella viventium. Qui animated corpse, cricket bat max brucks terribilem incessu zomby. The voodoo sacerdos flesh eater, suscitat mortuos comedere carnem virus.", 
    "published": false, 
}

Generic Views

  • CreateAPIView
  • ListAPIView
  • RetrieveAPIView
  • DestroyAPIView
  • UpdateAPIView
  • ListCreateAPIView
  • RetrieveUpdateAPIView
  • RetrieveDestroyAPIView
  • RetrieveUpdateDestroyAPIView
from rest_framework import generics
class TalkListView(generics.ListAPIView):
	pass

Filtering on the User

class TalkListView(generics.ListAPIView)
    def get_queryset(self):
        user = self.request.user
        return Purchase.objects.filter(purchaser=user)

Filtering on the URL

url(r'^rest/user/(?P<username>\w+)/talk/(?P<pk>\d*)$', TalkListView.as_view())

class TalkListView(generics.ListAPIView)
    def get_queryset(self):
        username = self.kwargs['username']
        return Purchase.objects.filter(purchaser__username=username)

Permissions

  • AllowAny
  • IsAuthenticated
  • IsAdminUser
  • IsAuthenticatedOrReadOnly
  • DjangoModelPermissions
  • DjangoModelPermissionsOrAnonReadOnly
  • DjangoObjectPermissions
from rest_framework import generics
class TalkListView(generics.ListAPIView):
    permission_classes = (permissions.DjangoObjectPermissons,)

Throttling

REST_FRAMEWORK = {
    'DEFAULT_THROTTLE_CLASSES': (
        'rest_framework.throttling.AnonRateThrottle',
        'rest_framework.throttling.UserRateThrottle'
    ),
    'DEFAULT_THROTTLE_RATES': {
        'anon': '100/day',
        'user': '1000/day'
    }        
}

Questions?