djangorestframework 框架的使用(二)

创建一个序列化类
serializers.py 中,默认有 create()update() 方法

# -*- coding:utf-8 -*-
from .models import *
from rest_framework import serializers

class TodoSerializer(serializers.Serializer):
    id = serializers.IntegerField()
    done = serializers.BooleanField(default=False)
    task = serializers.CharField(max_length=1000)
    is_delete = serializers.BooleanField(default=False)
    ct = serializers.CharField(max_length=50)

    def create(self, validated_data):
        """
        创建并返回一个todo
        """
        return Todo.todo.create(**validated_data)

    def update(self, instance, validated_data):
        """
        更新返回一个已经存在的todo
        """
        instance.done = validated_data.get("done", instance.done)
        instance.task = validated_data.get("task", instance.task)
        instance.is_delete = validated_data.get("is_delete", instance.is_delete)
        instance.ct = validated_data.get("ct", instance.ct)
        instance.save()
        return instance

JSONResponse
JSONRSponse 子类继承 HTTPResponse 返回 json 数据,在views.py文件中

from rest_framework.renderers import JSONRenderer
from django.http import HttpResponse

class JSONResponse(HttpResponse):
    """
    返回 json 数据
    """
    def __init__(self, data, **kwargs):
        content = JSONRenderer().render(data)
        kwargs['content_type']='application/json'
        super(JSONResponse, self).__init__(content, **kwargs)

视图APIView类
基于视图的类重新视图,在TodoList类可以返回所有的Todo列表和新增一个todo;在TodoDetail 类可以返回一个todo,更新和删除一个todo

from django.shortcuts import render
from django.http import HttpResponse
from django.http import Http404
from .models import Todo

from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.renderers import JSONRenderer
from rest_framework import status
from .serializers import TodoSerializer

class JSONResponse(HttpResponse):
    """
    返回json
    """
    def __init__(self, data, **kwargs):
        content = JSONRenderer().render(data)
        kwargs['content_type']='application/json'
        super(JSONResponse, self).__init__(content, **kwargs)

class TodoList(APIView):
    """
    所有的 todo,或创建一个新的todo
    """
    def get(self, request, format=None):
        todos = Todo.todo.filter(is_delete=False)
        serializer = TodoSerializer(todos, many=True)
        return Response(serializer.data)

    def post(self, request, format=None):
        serializer = TodoSerializer(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)


class TodoDetail(APIView):
    """
    获得,更新或创建一个todo
    """
    def get_object(self, pk):
        try:
            return Todo.todo.get(pk=pk)
        except Todo.DoesNotExist:
            raise Http404

    def get(self, request, pk, format=None):
        todo = self.get_object(pk)
        serializer = TodoSerializer(todo)
        return Response(serializer.data)

    def put(self, request, pk, format=None):
        todo = self.get_object(pk)
        serializer = TodoSerializer(todo, request.data)
        if serializer.is_valid():
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, pk, format=None):
        todo = self.get_object(pk)
        todo.delete()
        return  Response(status=status.HTTP_204_NO_CONTENT)

urls.py

from django.conf.urls import url
from . import views

urlpatterns = [
    ...
    url(r'^api/todos/$', views.TodoList.as_view()),
    url(r'^api/todos/(?P[0-9]+)/', views.TodoDetail.as_view())
]

测试
在浏览器中,输入http://127.0.0.1:8000/api/todos/ 获取所有的todo

todo列表.png

在浏览器中,输入http://127.0.0.1:8000/api/todos/9/ 获取id为9的todo

todo.png

你可能感兴趣的:(djangorestframework 框架的使用(二))