def get_ads_insight(self, account_id, from_time, to_time): """sample_response:: <api.Cursor> [ <AdsInsights> { "ad_name": "Ad name here", "adset_name": "Sample name", "campaign_id": "123456789", "campaign_name": "Campaign Test name", "cost_per_unique_click": "0.727143", "cpc": "0.727143", "ctr": "1.62037", "date_start": "2019-12-10", "date_stop": "2019-12-10", "spend": "5.09", "clicks": "7", "unique_clicks": "7" }, ]""" params = self.build_params(from_time, to_time) the_ad_account = AdAccount(account_id) try: async_job = the_ad_account.get_insights_async(fields=self.fields, params=params) status = async_job.remote_read() while status['async_percent_completion'] < 100: time.sleep(1) status = async_job.remote_read() result = async_job.get_result() insight_data_list = [] for item_ad_insight in result._queue: temp_dict = {} for _key in self.fields: try: temp_dict.update({ _key: item_ad_insight.__getitem__(_key), }) except KeyError: temp_dict.update({ _key: '', }) if temp_dict: insight_data_list.append(temp_dict) for k in self.required_merged_field_list: self.final_data.update( {k: self.add_value_by_key(k, insight_data_list)}) if len(insight_data_list) > 0: remaining_fields_set = set(self.fields) ^ set( self.required_merged_field_list) for f in remaining_fields_set: # remaining fields has same value of all items of the list. That's why only first item is considered self.final_data.update( {f: insight_data_list[0].get(f, '')}) except FacebookRequestError: pass # print(er) return self.final_data
#Wait till all the data is pulled def wait_for_async_job(async_job): async_job.api_get() while async_job[ AdReportRun.Field.async_status] != 'Job Completed' or async_job[ AdReportRun.Field.async_percent_completion] < 100: time.sleep(1) async_job.api_get() # Iterate through the adaccounts for account in adAccounts: # Create an addaccount object from the adaccount id to make it possible to get insights tempaccount = AdAccount(account[AdAccount.Field.id]) # Grab insight info for all ads in the adaccount ads = tempaccount.get_insights_async(fields=params.get('fields'), params=params) wait_for_async_job(ads) x = ads.get_result() #campaigns = tempaccount.get_campaigns(fields=[Campaign.Field.name,Campaign.Field]) # Iterate through all accounts in the business account for ad in x: # Set default values in case the insight info is empty date_of_report = todaydate account_id = "" account_name = "" action_values = "" actions = "" actions_link_click = "" actions_post_reaction = "" actions_post = "" actions_onsite_conversion_post_save = ""