• 接口设计及实现单查群查接口


    基于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()
  • 相关阅读:
    [LeetCode] Coin Change
    [LeetCode] House Robber
    [LeetCode] Lowest Common Ancestor of a Binary Search Tree
    [LeetCode] Remove Element
    [LeetCode] Merge Two Sorted Lists
    [LeetCode] Duplicate Emails
    svn propset svn:ignore
    WebLogic11g-负载分发
    WebLogic11g-集群相关概念
    WebLogic11g-半小时让你的domain集群化
  • 原文地址:https://www.cnblogs.com/baohanblog/p/12324293.html
Copyright © 2020-2023  润新知