【DRF】4. DRF视图开发RESTful API接口
四种方式:
- 函数式编程: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')
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律