Exemplo n.º 1
0
def calc_shop_core(request):
    """
        计算店铺核心词
    :param request:
    :return:
    """
    shop_id = int(request.user.shop_id)
    ck, _ = CoreKeyword.objects.get_or_create(shop_id=shop_id,
                                              defaults={
                                                  'kw_dict_list': [],
                                                  'update_time': None
                                              })
    condition = "ok"
    if ck.status:
        condition = "doing"
    else:
        if time_is_recent(ck.update_time, days=7):
            if not time_is_someday(
                    ck.report_sync_time):  # 如果当天也已经同步过报表了,则不再去同步
                Thread(target=ck.sync_current_report).start()
                condition = "ok"
            if ck.status:
                condition = "doing"
        else:
            Thread(target=ck.calc_top_keywords).start()
            condition = "doing"
    refresh_time = ck.update_time
    return {'errMsg': '', 'condition': condition, 'refresh_time': refresh_time}
Exemplo n.º 2
0
def quick_oper(request):
    '''触发页面上的“加大投入/减小投入”'''
    try:
        shop_id = int(request.user.shop_id)
        campaign_id = int(request.POST['campaign_id'])
        adg_id_list = request.POST.getlist("adg_id_list[]")
        adg_id_list = [int(adg_id) for adg_id in adg_id_list]
        stgy = int(request.POST['stgy'])
        opter, opter_name = analysis_web_opter(request)
        mnt_campaign = MntCampaign.objects.get(campaign_id = campaign_id, shop_id = shop_id)
        now = datetime.datetime.now()
        result = 1
        if adg_id_list:
            MntTaskMng.generate_quickop_task(shop_id = mnt_campaign.shop_id, campaign_id = mnt_campaign.campaign_id, mnt_type = mnt_campaign.mnt_type, stgy = stgy, adgroup_id_list = adg_id_list)
            adg_coll.update({'shop_id': shop_id, 'campaign_id':campaign_id, '_id':{'$in': adg_id_list}},
                            {'$set':{'quick_optime': now}}, multi = True)
        else:
            if not mnt_campaign.quick_optime or not time_is_someday(mnt_campaign.quick_optime):
                MntTaskMng.generate_quickop_task(shop_id = shop_id, campaign_id = mnt_campaign.campaign_id, mnt_type = mnt_campaign.mnt_type, stgy = stgy)
                mnt_campaign.quick_optime = now
                mnt_campaign.save()
            else:
                result = 2
        # 写入操作记录
        stgy_name = '加大投入' if stgy == 1 else '减小投入'
        opt_type = 15 if stgy == 1 else 16
        adg_ids = '、'.join([str(adg_id) for adg_id in adg_id_list])
        mnt_quick_oper_log(shop_id, campaign_id, adg_id_list, stgy_name, opter = opter, opter_name = opter_name)
        if adg_id_list:
            return {'errMsg':'', 'result':result, 'stgy':stgy, 'adg_id_list':adg_id_list}
        else:
            return {'errMsg':'', 'result':result, 'stgy':stgy}
    except Exception, e:
        log.exception('mnt quick oper error, shop_id=%s, campaign_id=%s, e=%s' % (request.user.shop_id, campaign_id, e))
        return {'errMsg':e, 'result':0, 'stgy':stgy}
Exemplo n.º 3
0
 def increase_download(cls, shop_id, tapi, last_sync_time):
     # 判断上次更新时间是否是今天,如果不是今天则进行同步预算
     return cls.struct_download(
         shop_id=shop_id,
         tapi=tapi,
         sync_budget=(not time_is_someday(last_sync_time)) and True
         or False)
Exemplo n.º 4
0
 def download_crtrpt_byadgs(
     cls, shop_id, tapi, token, adg_tuple_list
 ):  # adg_tuple_list形如:[(adgroup_id, campaign_id, last_sync_time)]
     """根据adg_tuple_list来下载指定adgroup下对应的创意"""
     try:
         init_start_date = datetime.date.today() - datetime.timedelta(
             days=cls.Report.INIT_DAYS)
         valid_rpt_days = datetime.datetime.now().hour < 6 and 2 or 1
         end_date = datetime.date.today() - datetime.timedelta(
             days=valid_rpt_days)
         for adg in adg_tuple_list:
             last_date = adg[2].date()
             if last_date < init_start_date:
                 last_date = init_start_date
             elif last_date > end_date:
                 last_date = end_date
             if not time_is_someday(last_date):
                 Creative.download_crtrpt_byadg(shop_id=shop_id,
                                                campaign_id=adg[1],
                                                adgroup_id=adg[0],
                                                token=token,
                                                time_scope=(last_date,
                                                            end_date),
                                                tapi=tapi)
         log.info('download creative rpt OK, shop_id=%s' % shop_id)
         return True, ''
     except Exception, e:
         log.error('download creative rpt FAILED, shop_id=%s, e=%s' %
                   (shop_id, e))
         return False, e
Exemplo n.º 5
0
def quick_oper(request, dajax):
    """触发页面上的“加大投入/减小投入”"""
    try:
        shop_id = int(request.user.shop_id)
        campaign_id = int(request.POST['campaign_id'])
        stgy = int(request.POST['stgy'])
        opter, opter_name = analysis_web_opter(request)
        mnt_campaign = MntCampaign.objects.get(campaign_id=campaign_id)
        if not mnt_campaign.quick_optime or not time_is_someday(
                mnt_campaign.quick_optime):
            MntTaskMng.generate_quickop_task(
                shop_id=mnt_campaign.shop_id,
                campaign_id=mnt_campaign.campaign_id,
                mnt_type=mnt_campaign.mnt_type,
                stgy=stgy)
            # 不管执行成功或者失败,都不让再操作
            mnt_campaign.quick_optime = datetime.datetime.now()
            mnt_campaign.save()
            dajax.script('PTQN.mnt.quick_oper_back(%s);' % (stgy))
        else:
            dajax.script('PTQN.mnt.quick_oper_back(0);')
        stgy_name = '加大投入' if stgy == 1 else '减小投入'
        opt_type = 15 if stgy == 1 else 16
        opt_desc = '对托管的宝贝%s' % (stgy_name)
        mnt_quick_oper_log(shop_id,
                           campaign_id, [],
                           opt_desc,
                           opter=opter,
                           opter_name=opter_name)
    except Exception, e:
        log.exception(
            'mnt quick oper error, shop_id=%s, campaign_id=%s, e=%s' %
            (request.user.shop_id, campaign_id, e))
        dajax.script('PTQN.mnt.quick_oper_back(0);')
Exemplo n.º 6
0
def flow_control(request):
    '''对外部JAPI执行流控控制。因为api函数要调用api_router中的dispatch,貌似无法通过装饰器实现该逻辑'''
    if not request:
        return ''
    req_dict = request.REQUEST
    isv_key = req_dict.get('appkey', '')
    if isv_key:
        limit_count = Config.get_value('common.ISV_APICONTROL_%s' % isv_key,
                                       default={}).get(req_dict['method'],
                                                       None)
        if limit_count:
            call_count = CacheAdpter.get(
                CacheKey.WEB_ISV_APICOUNT % (isv_key, req_dict['method']),
                'web', ())
            if not call_count:
                call_count = (1, datetime.datetime.now()
                              )  # TODO 缓存中没有,从数据库取调用数,每间隔1小时,写入数据库

            if call_count[0] >= limit_count and time_is_someday(
                    dt=call_count[1], days=0):
                return {
                    "error_response": {
                        "code": 7,
                        "msg": "App Call Limited",
                        "sub_code":
                        "accesscontrol.limited-by-api-access-count",
                        "sub_msg": "This ban will last for 1 more seconds"
                    }
                }
            else:
                CacheAdpter.set(
                    CacheKey.WEB_ISV_APICOUNT % (isv_key, req_dict['method']),
                    (call_count[0] + 1, datetime.datetime.now()), 'web',
                    60 * 60 * 24)
    return ''
Exemplo n.º 7
0
def shop_core(request, template="shop_core.html"):
    """店铺核心词"""
    custom_column = []
    refresh_time = None
    condition = "ok"
    version_limit = True
    if test_permission(ATTENTION_CODE, request.user):
        version_limit = False

        shop_id = int(request.user.shop_id)
        custom_column = Account.get_custom_col(shop_id=shop_id)
        ck, _ = CoreKeyword.objects.get_or_create(shop_id=shop_id,
                                                  defaults={
                                                      'kw_dict_list': [],
                                                      'update_time': None
                                                  })

        condition = "ok"
        if ck.status:
            condition = "doing"
        else:
            if time_is_someday(
                    ck.update_time):  # update_time为None的场景在时间判断里已经有了
                condition = "ok"
            elif time_is_recent(ck.update_time, days=7):
                if not time_is_someday(
                        ck.report_sync_time):  # 如果当天也已经同步过报表了,则不再去同步
                    Thread(target=ck.sync_current_report).start()
                    condition = "doing"
                else:
                    condition = "ok"
            else:
                Thread(target=ck.calc_top_keywords).start()
                condition = "doing"
        refresh_time = ck.update_time

    resp_data = {
        "custom_column": custom_column,
        "refresh_time": refresh_time,
        "condition": condition,
        "version_limit": version_limit
    }

    return render_to_response(template,
                              resp_data,
                              context_instance=RequestContext(request))
Exemplo n.º 8
0
def mnt_campaign(request, dajax):
    shop_id = int(request.user.shop_id)
    campaign_id = int(request.POST['campaign_id'])
    rpt_days = int(request.POST.get('rpt_days', 1))

    try:
        mnt_camp = MntCampaign.objects.get(shop_id=shop_id,
                                           campaign_id=int(campaign_id))

        if not mnt_camp.optimize_time:
            mnt_camp.optimize_time = '尚未优化'
        else:
            mnt_camp.optimize_time = time_humanize(mnt_camp.optimize_time)

        is_active = 1
        if mnt_camp.quick_optime and time_is_someday(mnt_camp.quick_optime):
            is_active = 0

        campaign = Campaign.objects.get(shop_id=shop_id,
                                        campaign_id=campaign_id)
        sum_rpt = campaign.get_summed_rpt(rpt_days=rpt_days)
        json_dict = {
            'total_cost': fen2yuan(sum_rpt.cost),
            'imp': sum_rpt.impressions,
            'click': sum_rpt.click,
            'ctr': '%.2f' % sum_rpt.ctr,
            'cpc': fen2yuan(sum_rpt.cpc),
            'total_pay': fen2yuan(sum_rpt.pay),
            'roi': '%.2f' % sum_rpt.roi,
            'conv': '%.2f' % sum_rpt.conv,
            'paycount': sum_rpt.paycount
        }
        max_price = 0
        if hasattr(mnt_camp, 'max_price'):
            max_price = format(mnt_camp.max_price / 100.0, '.2f')

        result = {
            'set': {
                'campaign_id': campaign_id,
                'title': campaign.title,
                'optimize_time': mnt_camp.optimize_time,
                'max_price': max_price,
                'budget': format(campaign.budget / 100.0, '.0f'),
                'is_active': is_active,
                'mnt_status': mnt_camp.mnt_status,
                'mnt_type': mnt_camp.mnt_type,
            },
            'rpt': json_dict,
        }
        dajax.script("PTQN.mnt.mnt_campaign_back(%s)" % json.dumps(result))
    except Exception, e:
        log.error('missing args or campaign not exist, shop_id = %s, e = %s' %
                  (shop_id, e))
        if 'query does not exist' in str(e):  # 删除缓存
            from apps.common.cachekey import CacheKey
            CacheAdpter.delete(CacheKey.WEB_MNT_MENU % shop_id, 'web')
        dajax.script('PTQN.alert("亲,请刷新页面重新操作!");')
Exemplo n.º 9
0
 def check_status_4rpt(self, klass, check_type='rpt'):
     """
     0.报表、UDP下载
     1.状态OK-->时间是否今天-->不必下载
                     | -->下载
     2.状态FAILED-->重新下载
     3.状态DOING -->检查上次成功时间是否是今天-->不必下载
                                 |---->检查运行时间是否在10分钟内--->等待
                                                     |------>重新下载
     4.状态是空-->初始化下载
     """
     # TODO: wangqi 20140711 下载报表的控制写的不够好,有空可以优化,没有利用好缓存的状态
     cls_name = get_klass_name(klass)
     status_result = parse_status(
         getattr(self, '%s%s_status' % (cls_name, check_type)))
     if status_result:
         status, last_time = status_result[0], status_result[1]
         if status in ('OK', 'EMPTY'):
             if time_is_someday(last_time):
                 return False, None
             else:
                 return True, last_time
         elif status == 'FAILED':
             return True, last_time
         elif status == 'DOING':
             if time_is_someday(last_time):
                 return False, None
             else:
                 if time_is_recent(status_result[2],
                                   minutes=cls_name == 'keyword' and 40
                                   or 10):  # 下载关键词报表时,这个时间限制可以大一些
                     return False, None
                 else:
                     return True, last_time
     else:
         # TODO: wangqi 20151102 这里先这样写吧,后期把status去掉,数据库只保存成功下载的时间即可
         return True, datetime.datetime.today() - datetime.timedelta(
             days=klass.Report.INIT_DAYS)
Exemplo n.º 10
0
    def tapi(self):
        if not hasattr(self, '_tapi'):
            tapi = get_tapi(shop_id=self.shop_id)
            if not time_is_someday(self.api_valid_time):
                is_ok, _ = QNApp.test_api(tapi)
                if not is_ok:
                    SessionCache.del_cache(self.shop_id)
                    tapi = get_tapi(shop_id=self.shop_id)
                    is_ok, reason = QNApp.test_api(tapi)
                    if not is_ok:
                        log.error("invalid tapi, error=%s" % reason)
                        tapi = None

                if tapi:
                    self.api_valid_time = datetime.datetime.now()
                    self.save()

            self._tapi = tapi
        return self._tapi
Exemplo n.º 11
0
def duplicate_check(request, template='duplicate_check.html'):
    shop_id = int(request.user.shop_id)
    dler_obj = Downloader.objects.get(shop_id=shop_id)

    def sync_data():
        dler_obj.auto_sync_struct()  # 先同步结构,再同步关键词报表
        dler_obj.sync_rpt(Keyword)

    kwrtp_isok = False
    status_result = parse_status(dler_obj.keywordrpt_status)
    if status_result:
        if time_is_someday(status_result[1]):
            if status_result[0] == 'OK':
                kwrtp_isok = True
        else:
            Thread(target=sync_data).start()
    else:
        Thread(target=sync_data).start()
    return render_to_response(template, {'kwrtp_isok': kwrtp_isok},
                              context_instance=RequestContext(request))
Exemplo n.º 12
0
def is_recent(value, args):
    """
            判断该对象是不是最近创建,或者最近删除等
    {{k|is_recent:'create_time,5'}}    返回True或者False,天数要注意,如果是一周内,天数是6,可以是负数
    {{k|is_recent:'create_time'}}    不带天数表示是否是当天
    """
    try:
        if value and args:
            args_list = args.split(',')
            if hasattr(value, args_list[0]):
                from apps.common.utils.utils_datetime import time_is_ndays_interval, time_is_someday
                if len(args_list) == 2:
                    return time_is_ndays_interval(getattr(value, args_list[0]),
                                                  int(args_list[1]))
                elif len(args_list) == 1:
                    return time_is_someday(getattr(value, args_list[0]))
                else:
                    raise Exception()
            else:
                raise Exception()
    except Exception, e:
        return False