美文网首页Django程序员
django-rest-framework 系列教程(三)- P

django-rest-framework 系列教程(三)- P

作者: 与蟒唯舞 | 来源:发表于2016-08-24 23:11 被阅读623次

    使用的环境:

    • python 2.7.10
    • Django 1.8.5
    • djangorestframework 3.4.4
    创建项目

    startproject rest_api

    创建 APP

    startapp task

    配置 rest_api/settings.py
    INSTALLED_APPS = (
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'rest_framework',
        'task',
    
    )
    
    配置 rest_api/urls.py
    # -*- coding:utf-8 -*-
    from django.conf.urls import url, include
    
    urlpatterns = [
        url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
        url(r'^api/', include('task.urls')),
    
    ]
    
    创建模型 task/models.py
    # -*- coding:utf-8 -*-
    from django.db import models
    
    
    class Task(models.Model):
        owner = models.ForeignKey('auth.User', related_name='tasks')
        title = models.CharField('标题', max_length=100)
        description = models.TextField('描述')
        completed = models.BooleanField('是否完成', default=False)
        create_date = models.DateTimeField('创建时间', auto_now_add=True)
    
        def __unicode__(self):
            return self.title
    
    序列化 task/serializers.py
    # -*- coding:utf-8 -*-
    from rest_framework import serializers
    from .models import Task
    
    
    class TaskSerializer(serializers.ModelSerializer):
        owner = serializers.ReadOnlyField(source='owner.username')
        class Meta:
            model = Task
            fields = ('id', 'title', 'description', 'completed', 'owner')
    
    
    创建 task/permissions.py
    # -*- coding:utf-8 -*-
    from rest_framework.permissions import IsAuthenticatedOrReadOnly, SAFE_METHODS
    
    
    class IsOwnerOrReadOnly(IsAuthenticatedOrReadOnly):
        def has_object_permission(self, request, view, obj):
            if request.method in SAFE_METHODS:
                return True
            return obj.owner == request.user
    
    视图 task/views.py
    # -*- coding:utf-8 -*-
    from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView
    
    from .models import Task
    from .serializers import TaskSerializer
    from .permissions import IsOwnerOrReadOnly
    
    
    class TaskMixin(object):
        queryset = Task.objects.all()
        serializer_class = TaskSerializer
        permission_classes = (IsOwnerOrReadOnly,)
    
    
    class TaskList(TaskMixin, ListCreateAPIView):
        def perform_create(self, serializer):
            serializer.save(owner=self.request.user)
    
    
    class TaskDetail(TaskMixin, RetrieveUpdateDestroyAPIView):
        pass
    
    路由 task/urls.py
    # -*- coding:utf-8 -*-
    from django.conf.urls import  url
    from . import views
    
    
    urlpatterns = [
        url(r'^tasks/$', views.TaskList.as_view(), name='task_list'),
        url(r'^tasks/(?P<pk>[0-9]+)$', views.TaskDetail.as_view(), name='task_detail'),
    
    ]
    
    Command Line
    curl http://localhost:8000/api/tasks/
    curl -X POST http://localhost:8000/api/tasks/ -d "title=basic&description=BasicAuthentication" -u admin:password
    curl -X PUT http://localhost:8000/api/tasks/1 -d "title=basic&description=BasicAuthentication&completed=True" -u admin:password
    curl -X DELETE http://localhost:8000/api/tasks/1 -u admin:password
    
    curl -X POST http://localhost:8000/api/tasks/ -H "X-CSRFToken: token" --cookie "sessionid=session; csrftoken=token" -d "title=session&description=SessionAuthentication" 
    # X-CSRFToken in headers just need be the same with csrftoken in cookie.
    

    上面是两种默认的认证方式(SessionAuthenticationBasicAuthentication),还有 TokenAuthentication

    通过以上,未授权认证的用户只能查看,只有授权认证的用户才可以进行创建,删除,更新操作。

    相关文章

      网友评论

      • 2d25a71a0d6d:应该说是像关闭api的管理页面,直接看json的数据
      • 2d25a71a0d6d:博主你好,我想问一下,**django-rest-framework**怎么关闭api的Django REST framework?
        我不需要浏览这个页面,我只需要json的页面。
        我在用django开发一个博客,但是我想使用**vue.js**,由于django的模板语言和vue冲突,所以想把博客的内容生成json格式的api接口,再通过vue在模板上渲染。不知道行不行?

      本文标题:django-rest-framework 系列教程(三)- P

      本文链接:https://www.haomeiwen.com/subject/ptmosttx.html