Skip to content
本页目录

1、可直接使用restframework中APIView,进行自定义GET\POST请求(适用微服务有较强逻辑需求的场景

from rest_framework.views import APIView

class ProvinceAreasView(APIView):
    """
    查询省数据
    get:
    查询省数据,补充缓存逻辑
    请求方式: GET /areas/
    """
    permission_classes = [IsAuthenticated]
    authentication_classes = [JWTAuthentication]

    def get(self, request):
        #补充缓存逻辑
        province_list = cache.get('province_list')
        if not province_list:
            try:
                province_model_list = Area.objects.filter(parent__isnull=True).order_by('id')
                province_list = []
                for province_model in province_model_list:
                    province_list.append({'id': province_model.id,'name': province_model.name})
                # 增加: 缓存省级数据
                cache.set('province_list', province_list, 3600)
            except Exception as e:
                return ErrorResponse(msg='省份数据错误')
        return SuccessResponse(data=province_list,msg='success')

class SubAreasView(APIView):
    """
    查询市或区数据
    get:
    子级地区:市和区县
    请求方式: GET /areas/(?P<pk>[1-9]\d+)/
    """
    permission_classes = [IsAuthenticated]
    authentication_classes = [JWTAuthentication]

    def get(self, request, pk):
        """提供市或区地区数据
        1.查询市或区数据
        2.序列化市或区数据
        3.响应市或区数据
        4.补充缓存数据
        """
        # 判断是否有缓存
        sub_data = cache.get('sub_area_' + pk)

        if not sub_data:

            # 1.查询市或区数据
            try:
                sub_model_list = Area.objects.filter(parent=pk).order_by('id')
                # 查询市或区的父级
                parent_model = Area.objects.get(id=pk)


                # 2.序列化市或区数据
                sub_list = []
                for sub_model in sub_model_list:
                    sub_list.append({'id': sub_model.id, 'name': sub_model.name})

                sub_data = {
                    'id':parent_model.id, # pk
                    'name':parent_model.name,
                    'subs': sub_list
                }

                # 缓存市或区数据
                cache.set('sub_area_' + pk, sub_data, 3600)
            except Exception as e:
                return ErrorResponse(msg='城市或区县数据错误')

        # 3.响应市或区数据
        return SuccessResponse(data=sub_data,msg="success")

2、给视图添加url、再application->urls.py中【#前端用户接口】处新添加

Released under the Apache License 2.0