def get_ads_or_adsets(self, campaign_ids, method): campaign_ids_slice = my_slice(campaign_ids, 50) campaign_ids_2_slice = my_slice(campaign_ids_slice, 50) fields_dict = { "ads-basic": { "fields": "name,id,status,adset_id,updated_time,campaign_id", "limit": 500, "dict_of_keys": {"type": "call_to_action_type"}, "method": "ads"}, "ads-layout": { "fields": "adcreatives{object_story_spec}", "limit": 200, "dict_of_keys": {"type": "call_to_action_type"}, "method": "ads"}, "adsets": { "fields": "campaign_id,id,name,status,start_time,updated_time,created_time,end_time", "limit": 500, "dict_of_keys": {}, "method": "adsets"}} get_data_params = fields_dict.get(method, False) if get_data_params: result = self.get_data_with_filtering(campaign_ids_2_slice, get_data_params["method"], get_data_params['fields'], "campaign.id", 'IN', get_data_params['limit']) result_data = [] for one_element_in_list in result: if method == 'ads-layout': mid_result_data = expand_dict(one_element_in_list['adcreatives'], get_data_params['dict_of_keys'], {}) mid_result_data['ad_id'] = one_element_in_list['id'] result_data.append(mid_result_data) else: result_data.append(expand_dict(one_element_in_list, get_data_params['dict_of_keys'], {})) return result_data else: return "Указан недопустимый метод."
def insert_rows(self, data_set_id, table_id, list_of_tuples): table_ref = self.client.dataset(data_set_id).table(table_id) table = self.client.get_table(table_ref) slice_data = my_slice(list_of_tuples, limit=3000) #TODO: Проверка на размер данных и автоматический подбор нужного limit for one_slice in slice_data: self.client.insert_rows(table, one_slice)
def get_keywords(self, campaign_ids_list): result_keywords = [] slice_ids = my_slice(campaign_ids_list, 10) self.headers_report['Client-Login'] = self.client_login field_names = ["Id", "Keyword", "AdGroupId", "CampaignId"] for ids in slice_ids: selection_criteria = {"CampaignIds": ids} keywords = self.__request(selection_criteria, field_names, "keywords", 10000, 0, [], "Keywords") result_keywords += keywords return result_keywords
def get_adsets(self, campaign_ids_list): result_adsets = [] slice_ids = my_slice(campaign_ids_list, 10) self.headers_report['Client-Login'] = self.client_login field_names = ["CampaignId", "Id", "Name", "Type"] for ids in slice_ids: selection_criteria = {"CampaignIds": ids} adsets = self.__request(selection_criteria, field_names, "adgroups", 10000, 0, [], "AdGroups") result_adsets += adsets return result_adsets
def get_ads(self, campaign_ids): campaign_ids = my_slice(campaign_ids, 100) ads_list = [] for campaign_ids_list in campaign_ids: campaign_ids_string = ",".join([str(x) for x in campaign_ids_list]) ads = self.__request('ads.getAds', request_type='get', account_id=self.account_id, campaign_ids=f"[{campaign_ids_string}]", client_id=self.client_id) for ad in ads: ads_list.append(ad) time.sleep(2) return ads_list
def get_day_stats(self, ids_type, list_of_ids, date_from, date_to, limit=2000): day_stat_list = [] ids_list = my_slice(list_of_ids, limit) for ids_stat_list in ids_list: ids_stat_string = ",".join([str(x) for x in ids_stat_list]) day_stats = self.__request('ads.getStatistics', request_type='get', account_id=self.account_id, ids_type=ids_type, ids=ids_stat_string, period="day", date_from=date_from, date_to=date_to) for DayStat in day_stats: for stat in DayStat['stats']: stat[DayStat['type'] + "_id"] = DayStat['id'] day_stat_list.append(stat) time.sleep(2) return day_stat_list
def data_to_insert(self, data_frame, integer_fields, float_fields, string_fields, data_set_id, table_id): if not data_frame.empty: data_frame = convert_data_frame_as_type(data_frame, integer_fields, float_fields, string_fields) data_frame_t = data_frame.T data_frame_t_dict = data_frame_t.to_dict() if data_frame_t_dict != {}: total = list(data_frame_t_dict.values()) sl_list = my_slice(total, 10000) for sl in sl_list: self.insert_json(data_set_id, table_id, sl) else: return "DataFrame is empty"
def get_ads_or_campaign_statistics(self, date_from, date_to, level): total_result = [] url_method = f"v6.0/{self.account}/insights?" date_from_dt = datetime.strptime(date_from, "%Y-%m-%d") date_to_dt = datetime.strptime(date_to, "%Y-%m-%d") list_of_days = [datetime.strftime(date_from_dt + timedelta(days=x), "%Y-%m-%d") for x in range(0, (date_to_dt - date_from_dt).days + 1)] list_of_days_slice = my_slice(list_of_days, 50) dict_of_params = { "ad": { "fields": "clicks,impressions,spend,video_p100_watched_actions,video_p25_watched_actions," "video_p50_watched_actions,video_30_sec_watched_actions,video_p75_watched_actions," "video_p95_watched_actions,video_thruplay_watched_actions,video_avg_time_watched_actions," "conversions,ad_id,ad_name,campaign_id,campaign_name,adset_id,adset_name", "limit": 50}, "campaign": { "fields": "impressions,clicks,spend,campaign_id,campaign_name,video_p100_watched_actions," "video_p25_watched_actions,video_p50_watched_actions,video_30_sec_watched_actions," "video_p75_watched_actions,video_p95_watched_actions,video_thruplay_watched_actions," "video_avg_time_watched_actions,conversions", "limit": 100}} get_data_params = dict_of_params.get(level, False) if get_data_params: count_list_of_days_slice = len(list_of_days_slice) for num, days in enumerate(list_of_days_slice, 1): batch = [] for day in days: time_range = "{'since':'%s','until':'%s'}" % (day, day) batch.append(self.create_betch(url_method, time_range=time_range, fields=get_data_params['fields'], limit=get_data_params['limit'], level=level, time_increment=1)) result_list, headers = self.get_batch_data(batch, [], url_method) for one in result_list: for key, value in one.items(): if "video_" in key: one[key] = value[0]['value'] total_result.append(one) if num != count_list_of_days_slice: self.check_headers(headers) return total_result else: return "Указан недопустимый уровень."
def get_demographics(self, demographics_list_ids, date_from, date_to, limit=2000): data_keys = {"sex": [], "age": [], "sex_age": [], "cities": []} demographics_list = my_slice(demographics_list_ids, limit) for demographics_id_list in demographics_list: demographics_ids_string = ",".join([str(x) for x in demographics_id_list]) demographics_response = self.__request('ads.getDemographics', request_type='get', account_id=self.account_id, ids_type="ad", ids=demographics_ids_string, period="day", date_from=date_from, date_to=date_to) for one in demographics_response: for element in one['stats']: for key, value in element.items(): if key in ['sex', 'age', 'sex_age', 'cities']: for one_element in value: arr = one_element.copy() arr[one['type'] + '_id'] = one['id'] arr['day'] = element['day'] data_keys[key].append(arr) return data_keys['sex'], data_keys['age'], data_keys['sex_age'], data_keys['cities']
def get_ads(self, campaign_ids_list): result_ads = [] slice_ids = my_slice(campaign_ids_list, 10) self.headers_report['Client-Login'] = self.client_login for ids in slice_ids: selection_criteria = {"CampaignIds": ids} field_names = [ "AdCategories", "AdGroupId", "CampaignId", "Id", "Type" ] params = { "TextAdFieldNames": [ "DisplayDomain", "Href", "Text", "Title", "Title2", "DisplayUrlPath" ], "TextImageAdFieldNames": ["Href"], "TextAdBuilderAdFieldNames": ["Href"], "CpcVideoAdBuilderAdFieldNames": ["Href"], "CpmBannerAdBuilderAdFieldNames": ["Href"], "CpmVideoAdBuilderAdFieldNames": ["Href"] } ads = self.__request(selection_criteria, field_names, "ads", 10000, 0, [], "Ads", **params) result_ads += [expand_dict(ad, {}, {}) for ad in ads] return result_ads