本文整理汇总了Python中facebookads.api.FacebookAdsApi类的典型用法代码示例。如果您正苦于以下问题:Python FacebookAdsApi类的具体用法?Python FacebookAdsApi怎么用?Python FacebookAdsApi使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了FacebookAdsApi类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: data
def data(request):
print(request)
# environmental variables for facebook auth
app_id = os.environ['APP_ID']
app_secret = os.environ['APP_SECRET']
access_token = os.environ['ACCESS_TOKEN']
FacebookAdsApi.init(app_id, app_secret, access_token)
campaign_id = request.GET['campaign-id']
def get_campaign_stats(campaign):
campaign = Campaign(campaign)
params = {
'data_preset': 'lifetime',
'fields': [
Insights.Field.impressions,
Insights.Field.unique_clicks,
Insights.Field.reach,
Insights.Field.cpm,
Insights.Field.spend,
]
}
data_set = campaign.get_insights(params=params)
return data_set[0]
data_set = get_campaign_stats(campaign_id)
data_set['cpm'] = str(data_set['cpm'])[:4]
context = {
'data_set': data_set,
'name': 'Campaign Breakdown',
}
print(data_set)
return render(request, 'campaigns_data/data.html', context)
示例2: __init__
def __init__(self, my_access_token, my_account_id, my_app_id = 'XXXXXXX', my_app_secret='XXXXXXXXXX'):
self.my_app_id = my_app_id
self.my_app_secret = my_app_secret
self.my_access_token = my_access_token
self.my_account_id = my_account_id
FacebookAdsApi.init(self.my_app_id, self.my_app_secret, self.my_access_token)
self.api = FacebookAdsApi.get_default_api()
示例3: init
def init(cls, app_id=None, app_secret=None, access_token=None,
account_id=None, api_version=None, pool_maxsize=10, max_retries=0):
# connection pool size is +1 because there also is the main thread that can also issue a request
session = FacebookSession(app_id, app_secret, access_token,
pool_maxsize+1, max_retries)
api = cls(session, api_version=api_version, threadpool_size=pool_maxsize)
cls.set_default_api(api)
# TODO: how to avoid this hack?
FacebookAdsApi.set_default_api(api)
if account_id:
cls.set_default_account_id(account_id)
示例4: request_new_fb_pixel
def request_new_fb_pixel():
from facebookads.api import FacebookAdsApi
from facebookads.objects import AdsPixel, AdUser
FacebookAdsApi.init(
app.config['FB_MY_APP_ID'],
app.config['FB_MY_APP_SECRET'],
app.config['FB_MY_ACCESS_TOKEN']
)
me = AdUser(fbid='me')
account = me.get_ad_accounts()[0]
pixel = account.get_ads_pixels([AdsPixel.Field.code])
return pixel.get_id(), pixel['code'].decode("utf-8")
示例5: get_fb_accounts
def get_fb_accounts(request):
FacebookAccount.objects.all().delete()
try:
fb_acc = SocialAccount.objects.get(user_id = request.user.id,provider='facebook')
fb_tok = SocialToken.objects.get(account=fb_acc)
except:
return HttpResponse("error connecting Social Accounts")
#setting the user information
my_app_id = '1604519246476149'
my_app_secret = '5a93aee73f1d2856dd542f53e268e483'
my_access_token = fb_tok.token
#gets the ad accounts in a single, pre-existing facebook account
FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token)
me = objects.AdUser(fbid='me')
my_accounts = list(me.get_ad_accounts())
#does it have ad accounts
if len(my_accounts) == 0:
return HttpResponse("no Ad Accounts Exist")
#important note, facebook allows us to only check upto 25
#accounts, we did the privacy note now just need to check if we can
#increase the amount
index = 0
for current_account in my_accounts:
if index == 25:
break
index = index + 1
fields=[
AdAccount.Field.account_id,
AdAccount.Field.name
]
current_account.remote_read(fields=fields)
if AdAccount.Field.name == "":
pass
account_model = FacebookAccount()
account_model.account_name = str(current_account[AdAccount.Field.name])
account_model.account_id = str(current_account[AdAccount.Field.account_id])
#account_model.report = report_model
if not account_model.account_name == "":
account_model.save()
示例6: auth
def auth(access_token=None):
if sys.__stdin__.isatty():
access_token = access_token or config['access_token']
FacebookAdsApi.init(
config['app_id'],
config['app_secret'],
access_token
)
else:
raise FacebookError(
"\n\n"
"## (/ o_o)/ ~ _|___|_ \n"
"## bootstrap.auth() should only be used in Python's interactive "
"shell. Try: python -i facebookads/bootstrap.py\n"
"## Or try using FacebookAdsApi.init()"
"\n"
)
示例7: facebookMain
def facebookMain(fbCred, emails_list):
act_id = fbCred['fb_user_id']
user_access_token = fbCred['user_token']
# user_access_token = 'CAAHsB1lutXABADNT3ppqATXZBdUwlfgEViIVlaHl5A14CpZBzoCvWi3qycaVdZAtLPnVFH5QY7EKY1UWYuYzvJptzrFaNcE8OXIOOYVo1hX33h8Ml2M9n5yyd7UJ3PHwOtixi6VgJNJY7sZAYY6b4CwqwCwZAjXir8aKAzmu6GMWZAutDKdSQ482SnawqJRIA7XVgR3K7HGIx1ZA4rOEFra'
# Login
FacebookAdsApi.init(my_app_id, my_app_secret, user_access_token)
ad_account = AdAccount(act_id)
### use this to login as yourself (if loged in on this computer)
# me = AdUser(fbid='me')
# my_account = me.get_ad_accounts()[0]
# Push emails to 3Targeting default list
audiences_list = getCustomAudiences(ad_account)
my_audiences = findAudienceByName(AUDIENCE_DEFAULT_NAME, audiences_list)
if my_audiences:
retVal = LoadCustomAudience(my_audiences[0], f=emails_list, datatype='email')
else:
retVal = CreateCustomAudience(ad_account, AUDIENCE_DEFAULT_NAME, description=AUDIENCE_DEFAULT_DESCRIPTION, f=emails_list, datatype='email')
return retVal
示例8: get_by_ids
def get_by_ids(cls, ids, params=None, fields=None, api=None):
api = api or FacebookAdsApi.get_default_api()
params = dict(params or {})
cls._assign_fields_to_params(fields, params)
params["ids"] = ",".join(map(str, ids))
response = api.call("GET", ["/"], params=params)
result = []
for fbid, data in response.json().items():
obj = cls(fbid, api=api)
obj._set_data(data)
result.append(obj)
return result
示例9: generate_record
def generate_record(self):
my_app_id = '881513028613192'
my_app_secret = '4252ecaa9b6b11ed5d72ddb8fc2528db'
my_access_token = 'CAAMhuz7vdEgBAPSuWuBSoCjsV0P45Y3KrqU7y5blqHVyM3XshUN9Dr3ZBNJWZCGJljogD6ZC2XSbqXT4D7I6PVH7isy4EBDqb1U3lB005yIM65ov4fCYUKz3J42kxMfwZBpVZABqBM5vOjZApE6ZC9PvOkRnc7mwZBMFZBnVXBiy37LgJJP2RQrZACpTac2s9INasZD'
FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token)
campaign = Campaign('6029907036952')
campaign.remote_read(fields=[
Campaign.Field.name,
Campaign.Field.effective_status,
Campaign.Field.objective,
])
params = {
'date_preset': 'last_30_days',
}
insights = campaign.get_insights(params=params)
self.write({'name': campaign['name']})
self.write({'result': insights[0]['actions'][0]['value']})
self.write({'reach': insights[0]['reach']})
self.write({'cost': insights[0]['cost_per_total_action']})
self.write({'amount_spent': insights[0]['spend']})
示例10: auth
def auth(cls):
"""
Prepare for Ads API calls and return a tuple with act_id
and page_id. page_id can be None but act_id is always set.
"""
config = cls.load_config()
if cls._is_authenticated:
return config['act_id'], config.get('page_id', None)
if config['app_id'] and config['app_secret'] \
and config['act_id'] and config['access_token']:
FacebookAdsApi.init(
config['app_id'],
config['app_secret'],
config['access_token'],
config['act_id'],
)
cls._is_authenticated = True
return config['act_id'], config.get('page_id', None)
else:
required_fields = set(
('app_id', 'app_secret', 'act_id', 'access_token')
)
missing_fields = required_fields - set(config.keys())
raise FacebookError(
'\n\tFile config.json needs to have the following fields: {}\n'
'\tMissing fields: {}\n'.format(
', '.join(required_fields),
', '.join(missing_fields),
)
)
示例11: __init__
def __init__(self, fbid=None, parent_id=None, api=None):
"""Initializes a CRUD object.
Args:
fbid (optional): The id of the object ont the Graph.
parent_id (optional): The id of the object's parent.
api (optional): An api object which all calls will go through. If
an api object is not specified, api calls will revert to going
through the default api.
"""
super(AbstractCrudObject, self).__init__()
self._api = api or FacebookAdsApi.get_default_api()
self._changes = {}
self._parent_id = parent_id
self._data['id'] = fbid
self._include_summary = True
示例12: __init__
def __init__(self, fbid=None, parent_id=None, api=None):
"""Initializes a CRUD object.
Args:
fbid (optional): The id of the object ont the Graph.
parent_id (optional): The id of the object's parent.
api (optional): An api object which all calls will go through. If
an api object is not specified, api calls will revert to going
through the default api.
"""
super(AbstractCrudObject, self).__init__()
self._api = api or FacebookAdsApi.get_default_api()
self._changes = {}
if (parent_id is not None):
warning_message = "parent_id as a parameter of constructor is " \
"being deprecated."
logging.warning(warning_message)
self._parent_id = parent_id
self._data['id'] = fbid
self._include_summary = True
示例13: remote_create_from_zip
def remote_create_from_zip(cls, filename, parent_id, api=None):
api = api or FacebookAdsApi.get_default_api()
open_file = open(filename, 'rb')
response = api.call(
'POST',
(parent_id, cls.get_endpoint()),
files={filename: open_file},
)
open_file.close()
data = response.json()
objs = []
for image_filename in data['images']:
image = cls(parent_id=parent_id)
image.update(data['images'][image_filename])
image[cls.Field.id] = '%s:%s' % (
parent_id[4:],
data['images'][image_filename][cls.Field.hash],
)
objs.append(image)
return objs
示例14: search
def search(cls, params=None, api=None):
api = api or FacebookAdsApi.get_default_api()
if not api:
raise FacebookBadObjectError(
"An Api instance must be provided as an argument or set as "
"the default Api in FacebookAdsApi.",
)
params = {} if not params else params.copy()
response = api.call(
FacebookAdsApi.HTTP_METHOD_GET,
"/".join((
FacebookSession.GRAPH,
FacebookAdsApi.API_VERSION,
'search'
)),
params,
).json()
ret_val = []
if response:
keys = response['data']
# The response object can be either a dictionary of dictionaries
# or a dictionary of lists.
if isinstance(keys, list):
for item in keys:
search_obj = TargetingSearch()
search_obj.update(item)
ret_val.append(search_obj)
elif isinstance(keys, dict):
for item in keys:
search_obj = TargetingSearch()
search_obj.update(keys[item])
if keys[item]:
ret_val.append(search_obj)
return ret_val
示例15: open
from __future__ import print_function
from __future__ import unicode_literals
from facebookads.objects import TargetingSearch
from facebookads.api import FacebookAdsApi
from facebookads.exceptions import *
config_file = open('./examples/docs/config.json')
config = json.load(config_file)
config_file.close()
ad_account_id = config['account_id']
access_token = config['access_token']
app_id = config['app_id']
app_secret = config['app_secret']
FacebookAdsApi.init(app_id, app_secret, access_token)
# _DOC open [SEARCH_GEOLOCATION_WITH_COUNTRY]
from facebookads.objects import TargetingSearch
params = {
'q': 'un',
'type': 'adgeolocation',
'location_types': ['country'],
}
resp = TargetingSearch.search(params=params)
print(resp)
# _DOC close [SEARCH_GEOLOCATION_WITH_COUNTRY]
# _DOC open [SEARCH_GEOLOCATION_WITH_REGION]
from facebookads.objects import TargetingSearch