APIView 简单接口编写

View.py

from ast import literal_eval

import snowflake.client  # 雪花算法存id

from rest_framework.response import Response
from rest_framework.views import APIView

from opportunity_market.checkresult import CheckResult
from opportunity_market.models import BusOpportunityFollow, BusOpportunitySetting
from opportunity_market.my_pagination import MyPagination
from opportunity_market.serializers import OpportunitySearchSerializer, BusOpportunityFollowSerializer, \
    BusOpportunitySettingSerializer
from read_db_app.models import GboOdsBusOpportunity


class OpportunitySearch(APIView):

    def get(self, request):     # 只接收get请求
        keyword = request.GET.get('keyword')
        country = request.GET.get('country_code')
        post_time_type = request.GET.get('post_time_type')
        quantity_type = request.GET.get('quantity_type')
        page = request.GET.get('page', 1)
        user_id = request.GET.get('user_id')
        if keyword.strip() == '':
            return Response(CheckResult.check('关键词为空, 请求失败'))
        # 发布时间筛选
        if post_time_type == '1':
            post_datetime = (datetime.datetime.now() - datetime.timedelta(hours=12))
            post_time = time.mktime(post_datetime.timetuple())
        elif post_time_type == '2':
            post_datetime = (datetime.datetime.now() - datetime.timedelta(days=1))
            post_time = time.mktime(post_datetime.timetuple())
        elif post_time_type == '3':
            post_datetime = (datetime.datetime.now() - datetime.timedelta(days=3))
            post_time = time.mktime(post_datetime.timetuple())
        elif post_time_type == '4':
            post_datetime = (datetime.datetime.now() - datetime.timedelta(weeks=1))
            post_time = time.mktime(post_datetime.timetuple())
        else:
            post_time = 0

        if quantity_type == '1':
            quantity_min = 1
            quantity_max = 100
        elif quantity_type == '2':
            quantity_min = 100
            quantity_max = 1000
        elif quantity_type == '3':
            quantity_min = 1000
            quantity_max = float("inf")  # 无穷大

        if country == '':
            opp_data = GboOdsBusOpportunity.objects.filter(bo_subject__icontains=keyword, post_time__gte=post_time,
                                                               quantity__gte=quantity_min, quantity__lte=quantity_max)   # __icontains: 忽略大小写模糊查询‘%s%’, __gte:大于等于, __lte:小于等于
        else:
            opp_data = GboOdsBusOpportunity.objects.filter(country_en_name__icontains=country, bo_subject__icontains=keyword,
                                                               post_time__gte=post_time, quantity__gte=quantity_min,
                                                               quantity__lte=quantity_max)
        mypage = MyPagination()
        page_roles = mypage.paginate_queryset(queryset=opp_data, request=request, view=self)   # 设置返回列表每页数据条数
        serializer_data = OpportunitySearchSerializer(instance=page_roles, many=True).data    # 序列化每页的取到的数据

        bo_id_list = [li.get('bo_id') for li in serializer_data]

        res = BusOpportunityFollow.objects.filter(bo_id__in=bo_id_list, user_id=user_id).only('bo_id')   # .only():经取回‘bo_id’字段的值
        bus_ser = BusOpportunityFollowSerializer(res, many=True).data

        for data in serializer_data:

            if data.get('bo_id') in [bus_bo_id.get('bo_id') for bus_bo_id in bus_ser]:    # 给序列化后,返回前端前的列表中的每条数据添加一个key:value值
                data.update({'follow_type': '1'})
            else:
                data.update({'follow_type': '2'})

        result = {
            'errcode': 0,
            'errmsg': '请求成功',
            'total': opp_data.count(),
            'page': page,
            'data': serializer_data
        }
        return Response(result)   # Rsponse 返回到前端

class buyerRecommendSetting(APIView):
    """商机推荐设置"""

    def post(self, request):
        user_id = request.POST.get('user_id')
        setting_value = request.POST.get('settting_value')

        try:
            s_values = literal_eval(setting_value)
        except:
            return Response(CheckResult.check('格式错误'))
        else:
            for value in s_values[0].values():
                if value.strip() == '':
                    return Response(CheckResult.check('存在推荐关键词为空,请求失败'))
            res = BusOpportunitySetting.objects.filter(user_id=user_id)
            if not res:
                setting_id = snowflake.client.get_guid()    # 雪花算法存id
                create_time = datetime.datetime.now()
                BusOpportunitySetting.objects.create(setting_id=setting_id, user_id=user_id,
                                                 settting_value=setting_value, create_time=create_time)   # 创建一条数据到数据库  

            else:
                res.update(settting_value=setting_value)     # 更新一条数据库指定字段数据

            result = {
                'errcode': 0,
                'errmsg': '提交成功'
            }
            return Response(result)


class OpportunityFollowSave(APIView):

    def post(self, request):
        user_id = request.POST.get('user_id')
        bo_id = request.POST.get('bo_id')
        follow_type = request.POST.get('follow_type')
        res = BusOpportunityFollow.objects.filter(user_id=user_id, bo_id=bo_id)   # 过滤筛选
        if not res:
            if follow_type == '1':
                follow_id = snowflake.client.get_guid()
                create_time = datetime.datetime.now()
                BusOpportunityFollow.objects.create(follow_id=follow_id, user_id=user_id, bo_id=bo_id,
                                                    create_time=create_time)   # 创建一条数据到数据库  
                    # (注:.create创建后,可以不用res.save(),因为创建相当于已经保存数据到数据库了,再save()可能就是保存了两次进数据库)
            elif follow_type == '2':
                BusOpportunityFollow.objects.filter(user_id=user_id, bo_id=bo_id).delete()    # 数据库删除指定的一条数据
            else:
                return Response(CheckResult.check('关注状态传入错误'))
            return Response({'errcode': 0, 'errmsg': '操作成功', })
        else:
            return Response(CheckResult.check('已关注'))

重写pagination设置页数:

my_pagination.py
from rest_framework import pagination


class MyPagination(pagination.PageNumberPagination):
    page_size = 10   # 每页数目
    page_query_param = 'page'
    page_size_query_param = 10  # 前端最多能涉及的每页数量

 

关于雪花算法模块:

# 安装:pip install pysnowflake

# 启动:snowflake_start_server
     # snowflake_start_server --address=127.0.0.1 --port=8910 --dc=1 --worker=1
# 引入
import snowflake.client
# 应用
guid = snowflake.client.get_guid()

 

posted @ 2020-05-27 11:44  yin_zhaozhao  阅读(342)  评论(0编辑  收藏  举报