【DRF】4. DRF视图开发RESTful API接口

发布时间 2023-05-03 23:46:13作者: chrjiajia

四种方式:

  • 函数式编程:function based view
  • 类视图:classed based view
  • 通用类视图:generic classed based view
  • DRF的视图集 Viewsets

原生Django FBV(Funciton based view)编写,应用的views.py

import json
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt

course_dict = {
    'name': '课程名称',
    'introduction': '课程介绍',
    'price': 9.99,
}

@csrf_exempt
def course_list(reqeust):
    if request.method == 'GET':
        return JsonResponse(course_dict)
        # 等同于:
        # return HttpResponse(json.dumps(course_dict), content_type='application/json')
    if request.method == 'POST':
        course = json.loads(reqeust.body.decode('utf-8'))
        # return JsonResponse(course, safe=False)
        return HttpResponse(json.dumps(course_dict), content_type='application/json')

原生Django CBV(Classed based view)编写,应用的views.py

import json
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views import View

course_dict = {
    'name': '课程名称',
    'introduction': '课程介绍',
    'price': 9.99,
}


class CourseList(View):
    def get(self, request):
        return JsonResponse(course_dict)

    @csrf_exempt
    def post(self, request):
        course = json.loads(reqeust.body.decode('utf-8'))
        return HttpResponse(json.dumps(course), content_type='application/json')

DRF