Permissions & Authentication - django-rest-framework part 2

Learn how to use basic authentication with your new API, and setup custom permissions to get fine grained precision of what can be done with data.

resources

Command Line

curl http://localhost:9000/api/tasks/
curl -X POST http://localhost:9000/api/tasks/ -d "title=make dinner&desciprtion=something other than steak" -u percent20:password
curl -X PUT http://localhost:9000/api/tasks/1 -d "title=make dinner&desciprtion=something other than steak&completed=True"
curl -X PUT http://localhost:9000/api/tasks/1 -d "title=make dinner&desciprtion=something other than steak&completed=True" -u percent20:password
curl -X DELETE http://localhost:9000/api/tasks/1
curl -X DELETE http://localhost:9000/api/tasks/1 -u percent20:password
models.py

from django.db import models

class Task(models.Model):
    owner = models.ForeignKey('auth.User', related_name='tasks')
    completed = models.BooleanField(default=False)
    title = models.CharField(max_length=100)
    description = models.TextField()
permissions.py
from rest_framework.permissions import BasePermission, SAFE_METHODS


class IsOwnerOrReadOnly(BasePermission):
    def has_object_permission(self, request, view, obj):
        if request.method in SAFE_METHODS:
            return True

        return obj.owner == request.user
serializers.py
from rest_framework import serializers

from task.models import Task


class TaskSerializer(serializers.ModelSerializer):
    owner = serializers.Field('owner.username')

    class Meta:
        model = Task
        fields = ('title', 'description', 'completed', 'owner')
urls.py
from django.conf.urls import patterns, url
from rest_framework.urlpatterns import format_suffix_patterns

from api.views import TaskList, TaskDetail

urlpatterns = patterns(
    'api.views',
    url(r'^tasks/$', TaskList.as_view(), name='task_list'),
    url(r'^tasks/(?P<pk>[0-9]+)$', TaskDetail.as_view(), name='task_detail'),
)

urlpatterns = format_suffix_patterns(urlpatterns)
views.py
from rest_framework.generics import (
    ListCreateAPIView, RetrieveUpdateDestroyAPIView)

from task.models import Task
from api.serializers import TaskSerializer
from api.permissions import IsOwnerOrReadOnly


class TaskMixin(object):
    queryset = Task.objects.all()
    serializer_class = TaskSerializer
    permission_classes = (IsOwnerOrReadOnly,)

    def pre_save(self, obj):
        obj.owner = self.request.user


class TaskList(TaskMixin, ListCreateAPIView):
    pass


class TaskDetail(TaskMixin, RetrieveUpdateDestroyAPIView):
    pass
comments powered by Disqus