def set_session(self, access_token): """' 构造Session,创建API""" self.session = FacebookSession(self.app_id, self.app_secret, access_token) self.api = FacebookAdsApi(self.session) self.access_token = access_token FacebookAdsApi.set_default_api(self.api)
def initialize_facebook(): """Initializes a Facebook API session object. Returns: An authorized Facebook API session object. """ session = FacebookSession(APP_ID, APP_SECRET, ACCESS_TOKEN) return FacebookAdsApi(session)
def __init__(self, app_id, app_secret, access_token): self.app_id = app_id self.app_secret = app_secret self.access_token = access_token self.fb_session = FacebookSession(self.app_id, self.app_secret, self.access_token) self.fb_api = FacebookAdsApi(self.fb_session) """ 设置一个默认的API对象 """ FacebookAdsApi.set_default_api(self.fb_api)
def obtain_fb_api(self): """ Returns FB api in order to use the services from the FB sdk. :return: FB api """ try: print(" >>> Abriendo archivo de credenciales...") cred_file = 'credentials.json' with open('/home/sebasgona/Documents/proyecto_fintech/fintech' + cred_file) as credentials_json: credentials = json.load(credentials_json) session = FacebookSession(credentials['app_id'], credentials['app_secret'], credentials['access_token']) api = FacebookAdsApi(session) print(" >>> Obteniendo FB API...") return api except Exception as e: print(" >>> ERROR al obtener FB API: \n\n" + str(e)) return None
pp = pprint.PrettyPrinter(indent=4) this_dir = os.path.dirname(__file__) config_filename = os.path.join(this_dir, 'config.json') config_file = open(config_filename) config = json.load(config_file) config_file.close() ### Setup session and api objects session = FacebookSession( config['app_id'], config['app_secret'], config['access_token'], ) api = FacebookAdsApi(session) if __name__ == '__main__': FacebookAdsApi.set_default_api(api) print('\n\n\n********** Reading objects example. **********\n') ### Setup user and read the object from the server me = AdUser(fbid='me') ### Read user permissions print('>>> Reading permissions field of user:') pp.pprint(me.remote_read(fields=[AdUser.Field.permissions])) ### Get first account connected to the user my_account = me.get_ad_account()
class Adapter: """ An object designed to make managing custom audiences a little easier. :params account: str, account id :params table: str, table name from database return :: container.Adapter object """ __session = FacebookSession(config.APP_ID, config.APP_SECRET, config.ACCESS_TOKEN) __api = FacebookAdsApi(__session) def __init__(self, account=None, table='customers'): FacebookAdsApi.set_default_api(self.__api) if account: self._account = 'act_{}'.format(account) self.__api.set_default_account_id = self._account self._audiences = AdAccount(self._account).get_custom_audiences( fields=[CustomAudience.Field.name, CustomAudience.Field.id]) self._responses = [] def _get_audience(self, audience_name): """ This retrieves an audience object based on a string name. :params audience_name: str, name of audience """ for audience in list(self.audiences): if audience['name'] == audience_name: audience_id = audience['id'] target = CustomAudience(audience_id) return target def _batch_users(self, obj, size=2500): """ This returns a generator that returns a list of lists of a specific size. :params obj: list, users list that needs to be batched :params size: int, the batch size """ for chunk in range(0, len(obj), size): try: yield obj[chunk:chunk + size] except IndexError: yield obj[chunk:len(obj)] def create_audience(self, name, desc=None): """ This creates an audience object. :params name: str, name of audience :params desc: str, description of audience """ if name in [audience['name'] for audience in self.audiences]: raise ValueError( 'Attempted to add audience. Audience with same name exists.') audience = CustomAudience(parent_id=self._account) audience[CustomAudience.Field.subtype] = CustomAudience.Subtype.custom audience[CustomAudience.Field.name] = '{}'.format(name) if desc: audience[CustomAudience.Field.description] = desc audience.remote_create() def delete_audience(self, name): """ This deletes an audience object. :params name: str, name of audience """ if name not in [audience['name'] for audience in self.audiences]: raise ValueError( 'Attempted to remove audience. Audience does not exist.') for audience in list(self.audiences): if audience['name'] == name: delete_id = audience['id'] audience = CustomAudience(delete_id) audience.remote_delete() def add_users(self, name, users): """ This bulk adds users to an audience object. :params name: str, name of audience :params users: list, list of users """ if not len(users): return print('Attempted to add users. No users in the list.') print('Adding {} users to {}'.format(len(users), name)) if not isinstance(users, list): raise TypeError target = self._get_audience(name) if len(users) > 10000: # User add limit is ~10000. batches = self._batch_users(users) for batch in batches: post_ = target.add_users(CustomAudience.Schema.email_hash, batch, is_raw=True) pprint.pprint(post_._body) else: post_ = target.add_users(CustomAudience.Schema.email_hash, users, is_raw=True) def remove_users(self, name, users): """ This bulk deletes users from an audience object. :params name: str, name of audience :params users: list, list of users """ if not len(users): return print('Attempted to remove users. No users in the list.') print('Removing {} users to {}'.format(len(users), name)) if not isinstance(users, list): raise TypeError target = self._get_audience(name) if len(users) > 500: # User delete limit is 500 < x < 1000. batches = self._batch_users(users, size=500) for batch in batches: target.remove_users(CustomAudience.Schema.email_hash, batch) else: target.remove_users(CustomAudience.Schema.email_hash, users) @property def audiences(self): return AdAccount(self._account).get_custom_audiences( fields=[CustomAudience.Field.name, CustomAudience.Field.id]) def __str__(self): return '<[Adapter Object]>' def __repr__(self): return '<Adapter Object [{}]>'.form(self._account)
def process_fb_change(change): fan_page = FacebookFanPage.objects.get(fan_page_id=change['page_id']) my_session = FacebookSession(FB_APP_ID, FB_APP_SECRET, fan_page.token) my_api = FacebookAdsApi(my_session) FacebookAdsApi.set_default_api(my_api) try: leadgen = Lead(change['leadgen_id']) lead_response = leadgen.remote_read() except FacebookRequestError as e: print("Leadgen_id ({0})- FacebookRequestError: {1}".format( change['leadgen_id'], e)) return HttpResponse(json.dumps({ 'status': 'error', 'code': 400 }), content_type='application/json') lead_response = lead_response['field_data'] try: form = FacebookAdCode.objects.select_related('formulario').get( code=change['ad_id']).formulario except FacebookAdCode.DoesNotExist as e: print("Ad_id ({0})- FacebookRequestError: {1}".format( change['ad_id'], e)) return HttpResponse(json.dumps({ 'status': 'error', 'code': 400 }), content_type='application/json') processed_lead = {} cont = Context() for pair in lead_response: key = slugify(pair['name']).replace("-", "_") value = pair['values'][0] processed_lead[key] = value cont.update({key: value}) processed_lead = json.dumps(processed_lead) tracking = TrackingFormularioDinamico(site=Site.objects.get_current(), sender=form.name[:200], utm_source='Facebook', utm_medium='', utm_campaign='', object_form=form, sent_by_mail=False) tracking.data = processed_lead tracking.save() recipients = stringIO.StringIO(form.recipient_list) recipient_lines = [line.strip('\n\r') for line in recipients.readlines()] recipient_list = [] for line in recipient_lines: recipient = line.strip('\n\r') name, email = re.split('\s*,\s*', recipient) recipient_list.append(force_text((email.strip('\n\r')).strip(' '))) cont.update({'now': datetime.datetime.now()}) form.send_notification_email(ctx=cont, recipient_list=recipient_list, adf_recipient_list=[form.adf_recipient], ignore_limit=True) tracking.sent_by_mail = True tracking.save()
def get_page_api(): page_token = get_page_access_token() session = FacebookSession(test_config.app_id, test_config.app_secret, page_token) return FacebookAdsApi(session)
def facebook_campaign_stats(adcampaign, start_date_str, end_date_str, allow_cache=False): session = FacebookSession(BUSINESS_APP_ID, BUSINESS_APP_SECRET, adcampaign.ad_account.access_token) api = FacebookAdsApi(session) FacebookAdsApi.set_default_api(api) params = { 'time_range': { 'since': start_date_str, 'until': end_date_str, }, 'fields': [ AdsInsights.Field.impressions, AdsInsights.Field.clicks, AdsInsights.Field.spend, AdsInsights.Field.actions, AdsInsights.Field.ctr, AdsInsights.Field.inline_link_clicks, AdsInsights.Field.inline_link_click_ctr, AdsInsights.Field.cpc, ], } cache_file = '/tmp/%s-%s-%s.json' % (adcampaign.fbid, start_date_str, end_date_str) if allow_cache and os.path.isfile(cache_file): last_modified = datetime.fromtimestamp(os.path.getmtime(cache_file)) if last_modified > datetime.now() - timedelta(hours=1): with open(cache_file, 'r') as cache_file: return json.load(cache_file) last_err = None # TODO(chesterwu): verify the API rate limit not exceeded. Ref - # developers.facebook.com/docs/marketing-api/api-rate-limiting for i in xrange(3): try: campaign = Campaign(adcampaign.fbid) campaign_api_response = campaign.remote_read(fields=[ Campaign.Field.effective_status, Campaign.Field.spend_cap ]) insights = campaign.get_insights(params=params) except FacebookError as e: last_err = e else: break else: raise Exception( 'Failed to retrieve Facebook data for Adcampaign %s: %s' % (adcampaign, str(last_err))) if insights: insight = insights[0] campaign_stats = { 'status': campaign_api_response.get('effective_status'), 'spend_cap': campaign_api_response.get('spend_cap'), 'impressions': insight['impressions'], 'clicks': insight['clicks'], 'spent': float(insight['spend']) * 100, 'ctr': insight['ctr'], 'link_clicks': insight['inline_link_clicks'], 'website_ctr': insight['inline_link_click_ctr'], 'cpc': insight['cpc'], } else: campaign_stats = { 'status': campaign_api_response.get('effective_status'), 'spend_cap': campaign_api_response.get('spend_cap'), 'impressions': 0, 'clicks': 0, 'link_clicks': 0, 'spent': 0, 'ctr': None, 'website_ctr': None, 'cpc': None, } with open(cache_file, 'w') as cache_file: json.dump(campaign_stats, cache_file) return campaign_stats