def router_message(result, request=None): result_dict = {'result': {}} try: data = DictWrapper.load_dict(json.loads(result)) data.content = DictWrapper.load_dict(json.loads(data.content)) handle_result = MsgManager.handle(data.topic, data) log.info("handled %s by %s, result=%s" % (data, data.topic, handle_result)) result_dict = {'result': {'result': handle_result}} except Exception, e: log.error('handle %s error, e=%s' % (result, e)) result_dict = {'result': {'result': u'处理消息时出错'}}
def select_adgroup(query_dict, opt_list, opt_cmd_str, user_id, request = None): """基于adgroup生成任务""" from apps.crm.models import UserOrder from apps.mnt.models import MntTaskMng from apps.subway.models_adgroup import adg_coll try: query_dict = json.loads(query_dict) psuser_id = int(user_id) adg_list = list(adg_coll.find(query_dict, {'shop_id':1, 'campaign_id':1, '_id':1})) if not adg_list: return {'result':'查询不到对象,无法操作!'} else: adg_dict = {} for adg in adg_list: temp_key = '%s-%s' % (adg['shop_id'], adg['campaign_id']) if temp_key not in adg_dict: adg_dict[temp_key] = [] adg_dict[temp_key].append(adg['_id']) uo = UserOrder.create_order(psuser_id = psuser_id, command_detail = opt_cmd_str, query_dict = str(query_dict), from_source = 0) if not uo: return {'result':'命令已生成!'} uo.task_id_list = MntTaskMng.generate_task_bycmd(adg_dict = adg_dict, opt_list = json.loads(opt_list), reporter = uo.id) # 注意:参数中一些int型的,页面上传回来是str,注意在函数中强转 uo.save() return {'result':'命令生成成功!'} except Exception, e: return {'result':'命令生成失败,原因:%s' % e}
def mobile_package(request): """ .获取关键词的移动数据 """ keyword_list, errorMsg = [], '' word_list = json.loads(request.POST.get('word_list', '[]')) tmp_list = SelectKeywordPackage.mobile_package(word_list) okay_count, temp_keyword_list, filter_field_list = SelectKeywordPackage.recommand_by_system( 200, tmp_list) for kw in temp_keyword_list: tmp_kw = [ kw.word, kw.cat_cpc or 30, kw.cat_pv, kw.cat_click, kw.cat_ctr, kw.cat_competition, kw.keyword_score, kw.new_price or 30, kw.coverage, kw.is_delete, 0, [] ] tmp_kw[10] = getattr(kw, 'is_ok', 0) keyword_list.append(tmp_kw) data = { 'keyword_list': sorted(keyword_list, key=lambda x: x[3], reverse=True)[:200], 'okay_count': okay_count, 'filter_field_list': filter_field_list, 'select_type': '', } return {'errMsg': errorMsg, 'data': data}
def load_danger_cats_info(): cache_key = 'danger_cats' danger_cats = CacheAdpter.get(cache_key, 'web') if not danger_cats: jobj = Cat.get_danger_cat_list() danger_cats = json.loads(jobj) CacheAdpter.set(cache_key, danger_cats, 'web', 60 * 60 * 24) return danger_cats
def add_new_item(request): '''全自动将新宝贝添加为托管 1. 将增加的宝贝添加为广告组 2. 将添加成功的广告组,设置成托管宝贝[注意数量限制],并且还要保存托管设置 3. 添加成功的宝贝,只提示个数;添加失败的宝贝,要提示原因 ''' errMsg = '' msg = '' result = {} opter, opter_name = analysis_web_opter(request) def add_items_common(shop_id, campaign_id, new_item_dict): """给定item_title_list来添加宝贝""" item_arg_list, added_id_list, failed_item_dict = [], [], {} if new_item_dict: tapi = get_tapi(request.user) item_list = Item.get_item_by_ids(shop_id = shop_id, item_id_list = new_item_dict.keys(), tapi = tapi, transfer_flag = True) # 从淘宝获取标准的item数据 temp_item_dict = {} # 获取部分宝贝信息 for item in item_list: # 绑定创意标题 added_item = new_item_dict.get(item['_id'], {}) if not added_item: continue item.update({'adgroup': {'title': TitleTransfer.remove_noneed_words(added_item['title1']), 'img_url': added_item['img_url1']}, 'creative': {'title': TitleTransfer.remove_noneed_words(added_item['title2']), 'img_url': added_item['img_url2']}, }) item_arg_list.append(item) temp_item_dict.update({item['_id']:[item['pic_url'], item['title']]}) if item_arg_list: # 导入宝贝 added_id_list, error_msg_dict = add_adgroups(shop_id = shop_id, campaign_id = campaign_id, item_arg_list = item_arg_list, tapi = tapi, opter = opter, opter_name = opter_name) for item_id, error_msg in error_msg_dict.items(): temp_item_info = temp_item_dict.get(item_id, ('', '')) failed_item_dict.update({item_id:(temp_item_info[0], temp_item_info[1], error_msg)}) del temp_item_dict return added_id_list, failed_item_dict shop_id = int(request.user.shop_id) camp_id = int(request.POST['camp_id']) new_item_dict = json.loads(request.POST['new_item_dict']) new_item_dict = {int(item_id):adg_crt for item_id, adg_crt in new_item_dict.items()} mnt_type = int(request.POST.get('mnt_type', 0)) try: success_adg_id_list, failed_item_dict = add_items_common(shop_id = shop_id, campaign_id = camp_id, new_item_dict = new_item_dict) msg = '添加成功 %s 个宝贝%%s,添加失败 %s 个宝贝!' % (len(success_adg_id_list), len(failed_item_dict)) result['success_count'] = len(success_adg_id_list) result['failed_count'] = len(failed_item_dict) except Exception, e: success_adg_id_list, failed_item_dict = [], {} log.exception('add items2 error, shop_id=%s, campaign_id=%s, e=%s' % (shop_id, camp_id, e)) msg = '添加成功 %s 个宝贝%%s,添加失败 %s 个宝贝!' % (0, len(new_item_dict)) errMsg = "未知错误"
def submit_keyword(request): """提交关键词修改""" shop_id = int(request.user.shop_id) kw_list = json.loads(request.POST.get('submit_list', '')) opter, opter_name = analysis_web_opter(request) updated_id_list, _, _, failed_id_list = update_kws_8shopid( shop_id, kw_list, opter=opter, opter_name=opter_name) return { 'update_kw': updated_id_list, 'failed_kw': failed_id_list, 'errMsg': '' }
def curwords_submit(request, dajax): '''提交关键词出价到直通车''' from apps.web.utils import update_kws_8shopid shop_id = int(request.user.shop_id) kw_list = json.loads(request.POST.get('data', [])) updated_id_list, _, _, fail_update_id_list = update_kws_8shopid( shop_id=shop_id, kw_list=kw_list) result = {'success': updated_id_list, 'fall': fail_update_id_list} dajax.script("PTQN.keyword_manage.kw_submit_callback(%s)" % (json.dumps(result))) return dajax
def update_mnt_adg(request): '''添加/取消托管adgroup''' errMsg = '' result = {} opter, opter_name = analysis_web_opter(request) try: shop_id = int(request.user.shop_id) camp_id = int(request.POST['camp_id']) mnt_adg_dict = json.loads(request.POST['mnt_adg_dict']) adg_id_list = [int(adg_id) for adg_id in mnt_adg_dict] flag = int(request.POST['flag']) # 1是加入托管, 0是取消托管, 2是将提交的宝贝批量加入托管并将剩下的宝贝取消托管 if mnt_adg_dict: if flag == 2: MntMnger.set_mnt_adgroup(shop_id, camp_id, mnt_adg_dict, opter, opter_name) elif flag == 1: MntMnger.set_mnt_adgroup(shop_id, camp_id, mnt_adg_dict, opter, opter_name) elif flag == 0: MntMnger.unmnt_adgroup(shop_id, camp_id, adg_id_list, opter, opter_name) result['adg_id_list'] = adg_id_list result['flag'] = flag else: result['msg'] = '还未选择任何宝贝' # 更改或添加创意 tapi = get_tapi(request.user) update_creative_dict = json.loads(request.POST.get('update_creative_dict', '{}')) new_creative_list = json.loads(request.POST.get('new_creative_list', '[]')) for creative_id, data in update_creative_dict.items(): creative_id = int(creative_id) adgroup_id, title, img_url = data update_creative(tapi = tapi, shop_id = shop_id, adgroup_id = adgroup_id, creative_id = creative_id, title = title, img_url = img_url, opter = opter, opter_name = opter_name) if new_creative_list: add_creative(tapi = tapi, shop_id = shop_id, campaign_id = camp_id, crt_arg_list = new_creative_list, opter = opter, opter_name = opter_name) result['success_msg'] = '将 %s 个宝贝%s托管' % (len(adg_id_list), (flag and '加入' or '取消')) result['success_count'] = len(adg_id_list) except Exception, e: log.info('set adgroups mnt status error, e= %s, shop_id = %s' % (e, request.user.shop_id)) errMsg = '托管宝贝失败,请与客服联系'
def check_parms_integrity(self): self.top_dict = json.loads(self.request.GET['authString']) self.top_sign = self.request.GET.get('sign') self.timestamp = self.request.GET.get('timestamp') if self.top_dict and self.top_sign and self.timestamp \ and self.request.GET.get('from', '') in ('qianniuAndroid', 'qianniuIphone'): self.timestamp = int(self.timestamp) self.nick = urllib.unquote( self.top_dict['taobao_user_nick'].encode()) self.top_access_token = self.top_dict['access_token'] return True else: return False
def update_cfg(request, dajax): error_msg = '' shop_id = int(request.user.shop_id) campaign_id = request.POST['campaign_id'] submit_data = json.loads(request.POST['submit_data']) mnt_type = int(request.POST.get('mnt_type', 1)) opter, opter_name = analysis_web_opter(request) try: if submit_data.has_key('budget'): try: campaign = Campaign.objects.exclude('rpt_list').get( shop_id=shop_id, campaign_id=campaign_id) except DoesNotExist, e: log.info('can not get campaign, campaign_id = %s' % campaign_id) dajax.script('PTQN.light_msg("亲,请刷新页面重新操作!","red");') return dajax old_budget = campaign.budget new_budget = submit_data['budget'] try: result_list, msg_list = update_campaign( shop_id=shop_id, campaign_id=int(campaign_id), record_flag=False, budget=new_budget, use_smooth=campaign.is_smooth and 'true' or 'false', opter=opter, opter_name=opter_name) if 'budget' in result_list: display_budget = lambda x: x == 20000000 and '不限' or ('%s元' % x) descr = '日限额由%s,修改为%s' % (display_budget( old_budget / 100), display_budget(new_budget)) udpate_cmp_budget_log(shop_id=shop_id, campaign_id=campaign_id, opt_desc=descr, opter=opter, opter_name=opter_name) else: raise Exception('<br/>'.join(msg_list)) except Exception, e: log.info('update campaign budget error, e = %s, shop_id = %s' % (e, shop_id)) if 'sub_msg":"日限额不得小于推广计划实时扣款金额' in str(e): dajax.script('PTQN.light_msg("日限额不得小于推广计划实时扣款金额!","red");') else: dajax.script('PTQN.light_msg("修改日限额失败","red");') return dajax
def curwords_submit_4monitor(request, dajax): '''提交关键词出价到直通车''' from apps.web.utils import update_kws_8shopid shop_id = int(request.user.shop_id) kw_list = json.loads(request.POST.get('data', [])) updated_id_list, _, _, fail_update_id_list = update_kws_8shopid( shop_id=shop_id, kw_list=kw_list) result_data = {'success': updated_id_list, 'fall': fail_update_id_list} func_name = 'curwords_submit_4monitor' func_desc = '获取某一宝贝关键词实时流量 -(宝贝关键词流量)' args = json.dumps(kw_list) result = json.dumps(result_data) TempMonitor.generetor_record(shop_id, func_name, func_desc, args, result) dajax.script("PTQN.kw_monitor.kw_submit_callback(%s)" % (json.dumps(result_data))) return dajax
def check_danger_cats(request): if request.method == 'POST': cat_id_list = json.loads(request.POST['cat_id_list']) cat_id_list = list(set(cat_id_list)) # 先去重 cat_id_list = [cat_id for cat_id in cat_id_list if int(cat_id) != 0] result = 'true' if cat_id_list: danger_cat_list = load_danger_cats_info()[request.user.shop_type] try: root_cat_dict = Cat.get_root_cat(cat_id_list=cat_id_list) except Exception, e: log.error('e = %s, cat_id_list = %s' % (e, cat_id_list)) return HttpResponse('false') root_cat_id_list = list(set(root_cat_dict.values())) result = 'false' if list( set(root_cat_id_list) & set(danger_cat_list)) else 'true' return HttpResponse(result)
def mnt_campaign_setter(request): error_msg = None shop_id = int(request.user.shop_id) mnt_type = int(request.POST.get('mnt_type')) campaign_id = int(request.POST['campaign_id']) set_flag = int(request.POST['set_flag']) and True or False # 设置为托管计划或者终止托管计划 opter, opter_name = analysis_web_opter(request) try: warn_msg_dict = {} if mnt_type not in [1, 2, 3, 4]: raise Exception("wrong_mnt_type") if set_flag: mnt_rt = int(request.POST.get('mnt_rt', 0)) # 是否启用实时引擎 mnt_bid_factor = int(request.POST.get('mnt_bid_factor', 0)) opt_wireless = int(request.POST.get('opt_wireless', 0)) max_price = int(float(request.POST['max_price']) * 100) mobile_max_price = int(float(request.POST['mobile_max_price']) * 100) budget = int(request.POST['budget']) mnt_index = int(request.POST['mnt_index']) kwargs = {'area': int(request.POST.get('area', 0)), 'schedule': int(request.POST.get('schedule', 0)), 'platform': int(request.POST.get('platform', 0))} warn_msg_dict = MntMnger.set_mnt_camp(campaign_id = campaign_id, flag = set_flag, mnt_index = mnt_index, mnt_type = mnt_type, opter = opter, opter_name = opter_name, max_price = max_price, mobile_max_price = mobile_max_price, budget = budget, mnt_rt = mnt_rt, mnt_bid_factor = mnt_bid_factor, opt_wireless = opt_wireless, **kwargs) else: warn_msg_dict = MntMnger.set_mnt_camp(campaign_id = campaign_id, flag = set_flag, mnt_type = mnt_type, opter = opter, opter_name = opter_name) except Exception, e: log.info('mnt_campaign_setter error: %s, mnt_type: %s, campaign_id: %s, shop_id: %s,' % (e, mnt_type, campaign_id, shop_id)) if str(e) == "no_permission": return {'errMsg':'', 'result':0, 'error_msg':'no_permission'} try: result, error_msg = json.loads(e.message) except: if hasattr(e, 'reason'): error_msg = (eval(e.reason))['error_response'].get('sub_msg', '淘宝发生未知错误,请联系顾问') else: error_msg = e.message if 'need to wait' in error_msg: error_msg = 'API接口超限'
def rob_record(request): """获取抢排名记录""" errMsg, data = '', {} keyword_id = int(request.POST['keyword_id']) data = MessageChannel.get_history([keyword_id]) result_data = {} for k, record_list in data.iteritems(): temp_list = [] for r_str in record_list: r_dict = json.loads(r_str) try: r_dict['exp_rank_range'][0] = Keyword.RANK_START_DESC_MAP[ r_dict['platform']][str(r_dict['exp_rank_range'][0])] r_dict['exp_rank_range'][1] = Keyword.RANK_END_DESC_MAP[ r_dict['platform']][str(r_dict['exp_rank_range'][1])] except Exception, e: r_dict['exp_rank_range'] = ['', ''] log.error('kw_id=%s, e=%s' % (keyword_id, e)) temp_list.append(json.dumps(r_dict)) result_data.update({k: temp_list})
def update_cfg(request): error_msg = '' shop_id = int(request.user.shop_id) campaign_id = request.POST['campaign_id'] submit_data = json.loads(request.POST['submit_data']) mnt_type = int(request.POST.get('mnt_type', 1)) try: opter, opter_name = analysis_web_opter(request) if submit_data.has_key('budget'): try: campaign = Campaign.objects.get(shop_id = shop_id, campaign_id = campaign_id) except DoesNotExist, e: log.info('can not get campaign, campaign_id = %s' % campaign_id) return {'errMsg':'亲,请刷新页面重新操作!'} old_budget = campaign.budget new_budget = submit_data['budget'] result_list, msg_list = update_campaign(shop_id = shop_id, campaign_id = int(campaign_id), record_flag = False, budget = new_budget, use_smooth = campaign.is_smooth and 'true' or 'false', opter = opter, opter_name = opter_name) if 'budget' in result_list: display_budget = lambda x: x == 20000000 and '不限' or ('%s元' % x) opt_desc = '日限额由%s,修改为%s' % (display_budget(old_budget / 100), display_budget(new_budget)) udpate_cmp_budget_log(shop_id = shop_id, campaign_id = campaign_id, opt_desc = opt_desc, opter = opter, opter_name = opter_name) else: return {'errMsg':'<br/>'.join(msg_list)} if submit_data.has_key('max_price'): try: mnt_campaign = MntCampaign.objects.get(shop_id = shop_id, campaign_id = campaign_id) except DoesNotExist, e: log.info('can not get mnt_campaign, campaign_id = %s' % campaign_id) return {'errMsg':'亲,请刷新页面重新操作!'} old_max_price = mnt_campaign.max_price old_mobile_max_price = mnt_campaign.real_mobile_max_price new_max_price = int(round(float(submit_data.get('max_price', old_max_price / 100.0)) * 100)) new_mobile_max_price = int(round(float(submit_data.get('mobile_max_price', old_mobile_max_price / 100.0)) * 100)) if new_max_price != old_max_price or new_mobile_max_price != old_mobile_max_price: mnt_campaign.max_price = new_max_price mnt_campaign.mobile_max_price = new_mobile_max_price change_cmp_maxprice_log(shop_id = shop_id, campaign_id = campaign_id, max_price = new_max_price, mobile_max_price = new_mobile_max_price, opter = opter, opter_name = opter_name) MntTaskMng.upsert_task(shop_id = shop_id, campaign_id = campaign_id, mnt_type = mnt_type, task_type = 2, adgroup_id_list = 'ALL') mnt_campaign.save()
try: Attention.change_attention_state(shop_id, adgroup_id, keyword_id, False) result = [keyword_id] except Exception, e: log.error('cancel attention error, shop_id=%s, keyword_id=%s, e=%s' % (shop_id, keyword_id, e)) result = [] finally: dajax.script("PTQN.keyword_manage.call_back_cancel_attention(%s)" % (json.dumps(result))) return dajax shop_id = int(request.user.shop_id) kw_list = json.loads(request.POST.get('data', [])) opter, opter_name = analysis_web_opter(request) updated_id_list, _, _, fail_update_id_list = update_kws_8shopid( shop_id=shop_id, kw_list=kw_list, opter=opter, opter_name=opter_name) result = {'success': updated_id_list, 'fall': fail_update_id_list} dajax.script("PTQN.keyword_manage.call_back_submit(%s)" % (json.dumps(result))) return dajax def auto_set_attention_kw(request, dajax): '''一键设置关键词''' from apps.qnyd.biz import set_attention_kw shop_id = int(request.user.shop_id) set_attention_kw(shop_id=shop_id)
if cat_id_list: base_dict = { 'cat_id': cat_id_list[-1], 'cat_name': '>'.join(cat_all_name), 'adgroup_total': total } cat_data[int(cat_id_list[-1])] = base_dict data = zlib.compress(json.dumps(cat_data), 5) crm_cache.set(key, data, 10 * 24 * 60 * 60) crm_cache.delete(CacheKey.CRM_CAT_ADG_STATISTICS_LOCK) # log.info('The space of statictics catetgory data is %s bytes, length=%s.' % (sys.getsizeof(data), len(data))) else: cat_data = json.loads(zlib.decompress(cat_data)) return cat_data def get_valid_account_list(): """获取有效的账户列表""" valid_list = crm_cache.get(CacheKey.CRM_VALID_ACCOUNT_FLAG) if not valid_list: try: valid_list = [] yes_time = date_2datetime(datetime.date.today() - datetime.timedelta(days=1)) for dl in dler_coll.find({'api_valid_time': { "$gte": yes_time }}, {'_id': 1}): try:
def decompress_obj(compressed_str): """解压缩""" temp_json = bz2.decompress(compressed_str) return json.loads(temp_json)