常见API编写方式(三种)
第一种API编写方式
第一种API的表现形式:
在course表中(多个数据操作):
可以进行:
数据查询
数据添加
在coursedetail表中(单个数据操作):
可以进行:
单个数据的查询
单个数据的修改
单个数据的删除
URL:
urlpatterns = [
url(r'courses/$',course.CoursesView.as_view()),
url(r'courses/(?P<pk>\d+)/$',course.CourseDetailView.as_view())
]
class CourseView(APIView):
def get(self,reqeust,*args,**kwargs):
'''
获取数据
:param reqeust:
:param args:
:param kwargs:
:return:
'''
ret = BaseResponse()
try:
queryset = models.Course.objects.all()
ser_obj = CourseSerializer(isinstance = queryset,many=True)
ret.data = ser_obj.data
except Exception as e:
ret.code = 1
ret.error = '获取数据失败'
return Response(ret.dict)
def post(self,request,*args,**kwargs):
'''
增加数据
:param request:
:param args:
:param kwargs:
:return:
'''
pass
class CourseDetailView(APIView):
def get(self,reqeust,pk,*arge,**kwargs):
'''
根据pk值获取对应的数据
:param reqeust:
:param pk:
:param arge:
:param kwargs:
:return:
'''
ret = BaseResponse()
try:
course_obj = models.Course.objects.filter(id=pk)
ser_obj = CourseSerializer(isinstance = course_obj)
ret.data = ser_obj.data
except Exception as e:
ret.code = 1
ret.error = '数据获取失败'
return Response(ret.dict)
def put(self,reqeust,pk,*args,**kwargs):
'''
修改数据
:param reqeust:
:param pk:
:param args:
:param kwargs:
:return:
'''
pass
def delete(self,request,*args,**kwargs):
'''
删除数据
:param request:
:param args:
:param kwargs:
:return:
'''
pass
第二种API编写方式