基于restful接口规范的接口设计
urlpatterns = [
# 资源books接口的设计
url(r'^books/$', views.BookAPIView.as_view()), # 群查、单增
url(r'^books/(?P<pk>d+)/$', views.BookAPIView.as_view()), # 单查、单删、单(整体|局部)改
]
实现单查群查接口
from rest_framework.views import APIView
from rest_framework.response import Response
from . import models
class BookAPIView(APIView):
def _multiple_get(self):
# 不能返回,数据是QuerySet[Obj, Obj],也不能强制转换list
# return list(models.Book.objects.all())
# QuerySet[dict, dict]
# print(models.Book.objects.values('name', 'price'))
# QuerySet[tuple, tuple]
# print(models.Book.objects.values_list('name', 'price'))
return Response(list(models.Book.objects.values('name', 'price')))
def _single_get(self, pk):
# return Response(models.Book.objects.filter(pk=pk).values('name', 'price').first())
# 开发阶段建议能用try的地方,不要使用if判断
try:
return Response(models.Book.objects.values('name', 'price').get(pk=pk))
except:
return Response('资源不存在')
# 单查、群查
def get(self, request, *args, **kwargs):
pk = kwargs.get('pk')
if pk:
# 单查逻辑
return self._single_get(pk)
else:
# 群查逻辑
return self._multiple_get()