Django REST实现步骤

安装django及djangorestframework

pip install django
pip install djangorestframework
(注:本文环境python2.7.9, django 1.9.2, djangorestframework 3.3.3)

创建django project及app

与创建django项目方法一样

修改setting.py

INSTALLED_APPS添加rest_framework
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    ...
]

添加REST_FRAMEWORK配置
REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAdminUser',),
    'PAGE_SIZE': 10
}


添加自己的model

models.py文件中定义question model
class Question(mongoengine.document.Document):
    question = mongoengine.fields.StringField(max_length = 10240, required = True)
    answer = mongoengine.fields.BooleanField(required = True)
    reason = mongoengine.fields.StringField(max_length = 1024)
    meta = {"db_alias": "wdbk", 'clooection': 'question'}


定义序列化类

新建serializers.py文件,定义序列化类,有三种方法:
(1) 继承于rest_framework.serializers.Serializer
class QuestionSerializer(serializers.Serializer):
    def create(self, validated_data):
        return Question.objects.create(**validated_data)

    def update(self, instance, validated_data):
        instance.question = validated_data.get('question', instance.question)
        instance.answer = validated_data.get('answer', instance.answer)
        instance.reason = validated_data.get('reason', instance.reason)
        instance.save()
        return instance
(2) 继承 于rest_framework.serializers.ModelSerializer
class QuestionSerializer(<span style="font-family: Arial, Helvetica, sans-serif;">serializers.ModelSerializer</span>):
    class Meta:
        model = Question
        fields = ('question', 'answer', 'reason')
 
(3) 在视图中自己实现序列化
可以参考 http://www.django-rest-framework.org/tutorial/1-serialization/#writing-regular-django-views-using-our-serializer


定义REST视图

有以下几种方法实现rest视图:
(1) 函数视图
自定义函数,使用api_view装饰器,在函数内部处理GET、POST等请求
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from models import Question
from serializers import QuestionSerializer

@api_view(['GET', 'POST'])
def question_list(request):
    if request.method == 'GET':
        questions = Question.objects.all()
        serializer = QuestionSerializer(questions, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = QuestionSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
然后在urls.py中加入视图函数即可
(2) 基于类的视图
定义类继承于APIView,并实现get, post等方法
from models import Question
from serializers import QuestionSerializer
from django.http import Http404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status


class QuestionList(APIView):
    def get(self, request, format=None):
        questions = Question.objects.all()
        serializer = QuestionSerializer(questions, many=True)
        return Response(serializer.data)

    def post(self, request, format=None):
        serializer = QuestionSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
在urls.py中添加视图类
urlpatterns += [
    url(r'^questions/$', views.QuestionList.as_view()),
]
(3)使用ViewSet
参考 http://www.django-rest-framework.org/tutorial/6-viewsets-and-routers/#tutorial-6-viewsets-routers


REST安全认证

客户端有三种认证方式 BasicAuthentication、SessionAuthentication、TokenAuthentication
需要在setting.py中配置默认的认证类
REST_FRAMEWORK = {
    # three auth way: session,basic,token
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAdminUser',),
    'PAGE_SIZE': 10
}
具体可以参考 http://www.django-rest-framework.org/api-guide/authentication/#authentication

http://blog.csdn.net/fragmentalice

你可能感兴趣的:(django,REST)