django框架实现restful风格的API开发

时间:2021-05-11 19:21:03

RESTful风格的要求:https://www.cnblogs.com/chichung/p/9933116.html

利用django原生的框架直接做RESTful的API开发是怎样的呢?感受一下:

import json
from django.http import JsonResponse, HttpResponse
from django.views import View
from user.models import Department


class DepartmentListAPIView(View):
    def get(self,request):
        """查询所有部门  GET     /departments/"""

        query_set = Department.objects.all()
        department_list = []
        for i in query_set:
            department_list.append({"id":i.id,"name":i.name,"create_date":i.create_date})
        # JsonResponse 可以把字典、列表转换为json.但是转换列表时需要指定,safe=False
        return JsonResponse(department_list,safe=False)


    def post(self,request):
        """新增一个部门
        restful要求url地址是/departments
        要求成功返回的状态码是201(创建成功)
        要求返回新生成的资源的对象"""
        json_str = request.body.decode()  # 二进制-->json字符串
        data_dict = json.loads(json_str)  # json字符串-->字典
        # 校验参数(略)
        department = Department()
        department.name = data_dict["name"]  # 字典获取值,[]或者.get(key)
        department.save()  # 字典-->对象
        dict_data = {    # 对象-->字典
            "id":department.id,
            "name":department.name,
            "create_date":department.create_date,
            "is_delete":department.is_delete
        }
        return JsonResponse(dict_data,status=201)  # 字典-->json字符串


class DepartmentDetailAPIView(View):
    def get(self,request,pk):
        """查询一个部门"""
        department = Department.objects.get(id=pk)  # 对象
        # 对象转化为字典
        date_dict = {
            "id":department.id,
            "name":department.name,
            "create_date":department.create_date,
            "is_delete":department.is_delete
        }
        return JsonResponse(date_dict)  # 字典-->json字符串

    def put(self,request,pk):
        """
        修改一个部门  PUT     /departments/<pk>/
        :param pk: 主键,部门id
        """
        json_str = request.body.decode()  # 二进制-->json字符串
        data_dict = json.loads(json_str)  # json字符串-->字典
        # 校验参数(略)
        department = Department.objects.get(id=pk)  # 获取要修改的对象
        department.name = data_dict.get("name")
        department.create_date = data_dict.get("create_date")
        department.save()
        # restful要求put方法返回修改的对象的全部属性
        data_dict = {  # 对象-->字典
            "id":department.id,
            "name":department.name,
            "create_date":department.create_date,
            "is_delete":department.is_delete
        }
        return JsonResponse(data_dict,status=200)

    def delete(self,request,pk):
        """删除一个部门"""
        count = Department.objects.get(id=pk).delete()
        if count == 0:
            return HttpResponse(status=404)
        return HttpResponse(status=204)  # restful要求删除成功返回204状态码

 

同时,urls的设置也要restful一点:

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^departments$',views.DepartmentListAPIView.as_view()),
    url(r'^departments/(?P<pk>\d+)$',views.DepartmentDetailAPIView.as_view())
]

 

结论:太麻烦了,还是得用 Django REST Framework啊。