Ejemplo n.º 1
0
    async def post(self, *args, **kwargs):
        re_data = {}
        param = loads(self.request.body.decode('utf8'))
        form = DeleteAdgroupHandlerForm.from_json(param)

        if not form.validate():
            self.set_status(404)
            for field in form.errors:
                re_data[field] = form.errors[field][0]
            return await self.finish(re_data)

        param = {'adGroupId': form.adGroupId.data}

        api = BaseApi(access_token=self.current_user.access_token)

        try:
            resp = await api.send_request(
                api_url='1/com.alibaba.p4p/alibaba.cnp4p.adgroup.delete',
                param=param)
        except HTTPClientError as e:
            await self.write_log(str(self.current_user.access_token),
                                 str(param),
                                 str(e),
                                 str(e.response.body.decode('utf8')),
                                 '删除推广单元失败',
                                 filename='delete_adgroup.log')
            return await self.finish(e.response.body.decode('utf8'))
        else:
            await self.finish(resp)
Ejemplo n.º 2
0
    async def post(self, *args, **kwargs):
        re_data = {}
        param = loads(self.request.body.decode('utf8'))
        form = UpdateAdgroupStatusForm.from_json(param)

        if form.validate():
            param = {
                'campaignId': form.campaignId.data,
                'adGroupId': form.adGroupId.data,
                'onlineState': form.onlineState.data
            }

            api = BaseApi(access_token=self.current_user.access_token)

            try:
                resp = await api.send_request(
                    api_url='1/com.alibaba.p4p/alibaba.cnp4p.adgroup.update',
                    param=param)
            except HTTPClientError as e:
                await self.write_log(str(self.current_user.access_token),
                                     str(param),
                                     str(e),
                                     str(e.response.body.decode('utf8')),
                                     '更新推广单元状态失败',
                                     filename='update_adgroup_status.log')
                self.set_status(404)
                return await self.finish(e.response.body.decode('utf8'))
            else:
                return await self.finish(resp)

        else:
            self.set_status(404)
            for field in form.errors:
                re_data[field] = form.errors[field][0]
            await self.finish(re_data)
Ejemplo n.º 3
0
    async def get(self, campaign_id, page_num, *args, **kwargs):

        form = GetAdgroup.from_json({
            'campaignId': campaign_id,
            'pageNo': page_num
        })

        if not form.validate():
            return await self.finish(self.error_handle(form))

        api = BaseApi(access_token=self.current_user.access_token)

        param = {
            'campaignId': form.campaignId.data,
            'pageNo': form.pageNo.data,
            'pageSize': 200,
        }

        try:
            resp = await api.send_request(
                api_url=
                '1/com.alibaba.p4p/alibaba.cnp4p.adgroup.bycampaignids.list',
                param=param)
        except HTTPClientError as e:
            await self.write_log(str(self.current_user.access_token),
                                 str(param),
                                 str(e.response.body.decode('utf8')),
                                 '获取推广计划下所有单元失败',
                                 filename='get_adgroup')
            self.set_status(404)
            return await self.finish(e.response.body.decode('utf8'))

        else:
            return await self.finish(resp)
Ejemplo n.º 4
0
    async def get(self, adgroup_id, *args, **kwargs):

        form = GetAdgroupKeywordHandler.from_json({'adGroupId': adgroup_id})

        if not form.validate():
            re_data = {}
            self.set_status(404)
            for field in form.errors:
                re_data[field] = form.errors[field][0]
            return await self.finish(re_data)

        api = BaseApi(access_token=self.current_user.access_token)

        param = {'adGroupId': form.adGroupId.data}

        try:
            resp = await api.send_request(
                api_url=
                '1/com.alibaba.p4p/alibaba.cnp4p.keyword.byadgroupid.list',
                param=param)
        except HTTPClientError as e:
            self.set_status(404)
            await self.write_log(str(self.current_user.access_token),
                                 str(param),
                                 str(e),
                                 str(e.response.body.decode('utf8')),
                                 '根据adGroupId获取网销宝关键词列表失败',
                                 filename='get_keywordlist.log')
            return await self.finish(e.response.body.decode('utf8'))
        else:
            await self.finish(resp)
Ejemplo n.º 5
0
    async def post(self, *args, **kwargs):
        re_data = {}
        param = self.request.body.decode('utf8')
        param = loads(param)
        form = UpdateCampaignForm.from_json(param)

        if form.validate():
            param = {
                'campaignId': form.campaignId.data,
                'budget': form.budget.data,
                'promoteArea': form.promoteArea.data,
                'schedule': self.get_schedule(form.schedule.data),
                'cositeFlag': form.cositeFlag.data
            }

            api = BaseApi(access_token=self.current_user.access_token)

            try:
                resp = await api.send_request(api_url='1/com.alibaba.p4p/alibaba.cnp4p.campaign.update', param=param)
            except HTTPClientError as e:
                await self.write_log(str(self.current_user.access_token), str(param), str(e),
                                     str(e.response.body.decode('utf8')), '修改推广计划失败',
                                     filename='update_campaign.log')
                self.set_status(404)
                re_data['code'] = 1012,
                re_data['message'] = '修改推广计划失败'
                return await self.finish(re_data)
            else:
                await self.finish(resp)

        else:
            self.set_status(404)
            for field in form.errors:
                re_data[field] = form.errors[field][0]
            await self.finish(re_data)
Ejemplo n.º 6
0
    async def post(self, *args, **kwargs):
        re_data = {}
        param = self.request.body.decode('utf8')

        param = loads(param)

        param = {
            'adGroupId': param['adGroupId'],
            'keywords': param['keywords']
        }

        api = BaseApi(access_token=self.current_user.access_token)

        try:
            resp = await api.send_request(
                api_url='1/com.alibaba.p4p/alibaba.cnp4p.keyword.add',
                param=param)
        except HTTPClientError as e:
            await self.write_log(str(self.current_user.access_token),
                                 str(param),
                                 str(e),
                                 str(e.response.body.decode('utf8')),
                                 '添加网销宝关键词失败',
                                 filename='post_keyword')
            self.set_status(404)
            re_data['code'] = 1010,
            re_data['message'] = '添加网销宝关键词失败'
            return await self.finish(re_data)
        else:
            await self.finish(resp)
Ejemplo n.º 7
0
    async def get(self, adgroup_id, *args, **kwargs):
        re_data = {}
        param = {'adGroupId': adgroup_id}

        form = GetAdgroupKeywordHandler.from_json(param)

        if not form.validate():
            self.set_status(404)
            for field in form.errors:
                re_data[field] = form.errors[field][0]
            return await self.finish(re_data)

        api = BaseApi(access_token=self.current_user.access_token)

        param = {'adGroupId': form.adGroupId.data, 'pageNo': 1, 'pageSize': 10}

        list_temp = []

        while param['pageNo'] <= 10:
            try:
                resp = await api.send_request(
                    '1/com.alibaba.p4p/alibaba.cnp4p.keyword.recommend.list',
                    param=param)
            except HTTPClientError as e:
                await self.write_log(str(self.current_user.access_token),
                                     str(param),
                                     str(e),
                                     str(e.response.body.decode('utf8')),
                                     '获取指定推广单元关键词失败',
                                     filename='get_keyword')
                self.set_status(404)
                re_data['code'] = 1009,
                re_data['message'] = '获取指定推广单元关键词失败'
                return await self.finish(re_data)
            else:
                result = loads(resp)
                list_temp += result['recommends']
                param['pageNo'] += 1

        # 过滤没有竞争指数的关键词
        list_ = list(filter(lambda x: 'pv' in x, list_temp))
        # 展示指数从大到小排序
        list_temp = sorted(list_,
                           key=lambda x: x['qualityScore'],
                           reverse=True)

        re_data['result'] = list_temp
        await self.finish(re_data)
Ejemplo n.º 8
0
    async def get(self, *args, **kwargs):

        api = BaseApi(self.current_user.access_token)

        try:
            resp = await api.send_request(
                api_url='1/com.alibaba.p4p/alibaba.cnp4p.campaign.areaList')
        except HTTPClientError as e:
            self.set_status(404)
            await self.write_log(str(self.current_user.access_token),
                                 str(e.response.body.decode('utf8')),
                                 '请求可投放地域列表出错',
                                 filename='get_area')

            return await self.finish(e.response.body.decode('utf8'))

        else:
            await self.finish(resp)
Ejemplo n.º 9
0
    async def get(self, campaign_id, page_num, *args, **kwargs):

        api = BaseApi(self.current_user.access_token)

        param = {
            'pageNo': page_num,
            'pageSize': 20,
            'needDetail': 'false',
            'needFreight': 'false'
        }

        # 获得卖家商品列表某一页
        try:
            rp = await api.send_request(
                api_url='1/com.alibaba.product/alibaba.product.list.get',
                param=param,
                timestamp=False)
        except HTTPClientError as e:
            await self.write_log(str(self.current_user.access_token),
                                 str(param),
                                 str(e.response.body.decode('utf8')),
                                 '获取商家商品列表失败',
                                 filename='get_offer')
            self.set_status(404)
            return await self.finish(e.response.body.decode('utf8'))

        else:
            # 解析数据
            rp = loads(rp)

            # 如果是空, 继续执行没有意义了
            if not rp['result']['pageResult']['resultList']:
                return await self.finish({'result': [], 'msg': '用户供应商品列表为空'})

            # 获取数据的所有商品id
            list_1 = []  # 商品id列表
            [
                list_1.append(result['productID'])
                for result in rp['result']['pageResult']['resultList']
            ]

        # =======================================================================================================

        # 商品id列表
        list_2 = []

        # 获取指定推广计划下的所有所有推广单元
        param = {
            'campaignId': campaign_id,
            'pageNo': 1,
            'pageSize': 200,
        }

        num = 1  # 固定请求最大次数
        while num <= 5:
            try:
                resp = await api.send_request(
                    api_url=
                    '1/com.alibaba.p4p/alibaba.cnp4p.adgroup.bycampaignids.list',
                    param=param)
            except HTTPClientError as e:
                await self.write_log(str(self.current_user.access_token),
                                     str(param),
                                     str(e.response.body.decode('utf8')),
                                     '获取推广计划下所有单元失败',
                                     filename='get_adgroup')
                self.set_status(404)
                return await self.finish(e.response.body.decode('utf8'))
            else:
                # 解析数据
                resp = loads(resp)

                # 第一次请求或后续请求没有结果, 退出循环
                if not resp['adgroups']:
                    break

                # 获取数据的所有商品id
                [
                    list_2.append(result['offerId'])
                    for result in resp['adgroups']
                ]

                # 获得单元总数
                total_num = resp['totalRow']

                # 单元总数大于等于200, value肯定大于等于1.0
                # 单元数小于200200, value肯定小于1.0
                value = total_num / 200

                # 请求一次就好, 数据要么小于200条, 要么正好等于200条
                if value <= 1:
                    break

                param['pageNo'] += 1
                num += 1

        # 只有一种情况, 当前推广计划下推广单元列表是空的, 直接返回全部商品
        if not list_2:
            return await self.finish({'result': rp, 'repeat_offer': []})

        result = list(set(list_1) & set(list_2))

        # 请求的当前商品列表 里 没有在投的推广单元
        if not result:
            return await self.finish({'result': rp, 'repeat_offer': []})

        # 当前商品列表里, 有在投的推广单元
        await self.finish({'result': rp, 'repeat_offer': result})
Ejemplo n.º 10
0
    async def post(self, *args, **kwargs):

        param = self.request.body.decode('utf8')

        form = CreateAdgroupForm.from_json(loads(param))

        if not form.validate():
            return await self.finish(self.error_handle(form))

        api = BaseApi(access_token=self.current_user.access_token)

        # 查询线上推广计划的修改时间
        param = {'campaignIdList': form.campaignId.data}
        try:
            resp = await api.send_request(
                api_url='1/com.alibaba.p4p/alibaba.cnp4p.campaign.list',
                param=param)
        except HTTPClientError as e:
            await self.write_log(str(self.current_user.access_token),
                                 str(param),
                                 str(e.response.body.decode('utf8')),
                                 '获取推广计划失败',
                                 filename='get_campaign')
            self.set_status(404)
            return await self.finish(e.response.body.decode('utf8'))
        else:
            resp = loads(resp)

            if not resp['campaigns']:
                self.set_status(404)
                return await self.finish({"error_message": "此账号没有这条推广计划"})

            # 线上推广计划修改时间
            modifiedtime = resp['campaigns'][0]['modifiedTime']

        # =====================================================================================================

        # 查询线下推广计划修改时间
        try:
            result = await self.application.objects.get(
                User_campaign.select(User_campaign.modifiedTime).where(
                    User_campaign.campaignId == form.campaignId.data))
        except User_campaign.DoesNotExist:
            self.set_status(404)
            return await self.finish({'error_message': '此推广计划不属于本app'})
        else:
            # 将models字典化
            result = model_to_dict(result)
            # 将线上和线下的修改时间进行对比
            if modifiedtime != str(result['modifiedTime']):
                self.set_status(404)
                return await self.finish({"error_message": "此推广计划已被污染, 弃掉"})

        # =====================================================================================================

        # 开始创建推广单元
        param = {
            'campaignId': form.campaignId.data,
            'onlineState': 1,
            'bidPrice': form.bidPrice.data,
            'offerId': form.offerId.data
        }
        try:
            resp = await api.send_request(
                api_url='1/com.alibaba.p4p/alibaba.cnp4p.adgroup.add',
                param=param)
        except HTTPClientError as e:
            await self.write_log(str(self.current_user.access_token),
                                 str(param),
                                 str(e.response.body.decode('utf8')),
                                 '创建推广单元失败',
                                 filename='post_adgroup')
            self.set_status(404)
            return await self.finish(e.response.body.decode('utf8'))
        else:
            resp = loads(resp)
            resp = resp['adgroup']

            try:
                await self.application.objects.create(
                    User_adgroup,
                    memberId=self.current_user.memberId,
                    auditState=resp['auditState'],
                    bidPrice=resp['bidPrice'],
                    campaignId=resp['campaignId'],
                    adGroupId=resp['adGroupId'],
                    createTime=resp['createTime'],
                    modifiedTime=resp['modifiedTime'],
                    offerId=resp['offerId'],
                    onlineState=resp['onlineState'],
                    title=resp['title'])
            except Exception as e:
                self.set_status(404)
                await self.write_log(str(self.current_user.access_token),
                                     str(resp),
                                     str(e),
                                     '增加推广单元失败',
                                     filename='write_adgroup')
                return await self.finish({'error_message': '增加推广单元失败'})
            await self.finish(resp)
Ejemplo n.º 11
0
    async def post(self, *args, **kwargs):

        param = self.request.body.decode('utf8')

        form = AddCampaignForm.from_json(loads(param))

        if not form.validate():
            return await self.finish(self.error_handle(form))

        api = BaseApi(self.current_user.access_token)

        param = {
            'title': form.campaign_name.data + f'-財源廣進-{strftime("%Y%m%d%H%M%S", localtime())}',
            'budget': form.budget.data,
            'onlineStatus': '1',
            'schedule': self.get_schedule(form.schedule.data),
            'cositeFlag': form.cositeFlag.data,
            'promoteArea': form.promoteArea.data
        }

        try:
            rp = await api.send_request(api_url='1/com.alibaba.p4p/alibaba.cnp4p.campaign.add', param=param)
        except HTTPClientError as e:
            await self.write_log(str(self.current_user.access_token),
                                 str(param),
                                 str(e.response.body.decode('utf8')),
                                 '创建推广计划失败',
                                 filename='post_campaign')
            self.set_status(404)
            return await self.finish(e.response.body.decode('utf8'))
        else:

            result = loads(rp)  # 解析成功数据

            try:
                await self.application.objects.create(User_campaign,
                                                      memberId=self.current_user.memberId,
                                                      campaignId=result['campaign']['campaignId'],
                                                      title=result['campaign']['title'],
                                                      budget=result['campaign']['budget'],
                                                      promoteArea=result['campaign']['promoteArea'],
                                                      schedule=form.schedule.data,
                                                      onlineStatus=result['campaign']['onlineStatus'],
                                                      settleStatus=result['campaign']['settleStatus'],
                                                      cositeFlag=result['campaign']['cositeFlag'],
                                                      createTime=result['campaign']['createTime'],
                                                      modifiedTime=result['campaign']['modifiedTime'])
            except Exception as e:
                await self.write_log(str(self.current_user.memberId),
                                     str(result['campaign']['campaignId']),
                                     str(result['campaign']['title']),
                                     str(result['campaign']['budget']),
                                     str(result['campaign']['promoteArea']),
                                     str(form.schedule.data),
                                     str(result['campaign']['onlineStatus']),
                                     str(result['campaign']['settleStatus']),
                                     str(result['campaign']['cositeFlag']),
                                     str(result['campaign']['createTime']),
                                     str(result['campaign']['modifiedTime']),
                                     str(e),
                                     '创建推广计划sql记录失败',
                                     filename='post_campaign')
                self.set_status(404)
                return await self.finish({'error_message': 'sql语句提交错误'})
            else:
                await self.finish(rp)
Ejemplo n.º 12
0
    async def get(self, *args, **kwargs):

        # 获取库里的数据
        campaign = await self.application.objects.execute(
            User_campaign.select(
                User_campaign.campaignId,
                User_campaign.modifiedTime
            ).where(
                User_campaign.memberId == self.current_user.memberId))

        # 库里没有数据后面就没有意义了, 因为必须以 库里数据和线上 共有的数据为准
        if not campaign:
            return await self.finish({'result': []})

        api = BaseApi(self.current_user.access_token)

        # 获取线上所有推广计划
        try:
            resp = await api.send_request(api_url='1/com.alibaba.p4p/alibaba.cnp4p.campaign.list')
        except HTTPClientError as e:
            await self.write_log(str(self.current_user.access_token),
                                 str(e.response.body.decode('utf8')),
                                 '获取推广计划失败',
                                 filename='get_campaign')
            self.set_status(404)
            return await self.finish(e.response.body.decode('utf8'))
        else:
            resp = loads(resp)

            # 线上没有任何推广计划, 说明库里的计划被用户手动删除了
            if not resp['campaigns']:
                return await self.finish({'result': [], 'msg': '线上没有任何推广计划'})

            # 库里数据格式化
            list_result = []
            for result in campaign:
                list_temp = []
                result = model_to_dict(result)
                list_temp.append(int(result['campaignId']))
                list_temp.append(str(result['modifiedTime']))
                list_result.append(tuple(list_temp))

            # 对线上数据进行格式化
            list_result_one = []
            for result in resp['campaigns']:
                list_temp = []
                list_temp.append(result['campaignId'])
                list_temp.append(result['modifiedTime'])
                list_result_one.append(tuple(list_temp))

            # 找出共有的数据, 找出没有被用户污染过的数据(用户手动修改, 使用其他工具修改本工具计划等), 确保是我们的数据
            result = set(list_result) & set(list_result_one)

            if not result:
                # 数据被污染过, 过滤掉
                return await self.finish({'result': [], 'msg': '没有符合我们的数据'})

            list_tmp = []
            for tmp in result:
                for tmp_2 in resp['campaigns']:
                    if tmp[0] == tmp_2['campaignId']:
                        list_tmp.append(tmp_2)
                        break

            await self.finish({'result': list_tmp})