当前位置: 首页>>代码示例>>Python>>正文


Python FacebookAdsApi.init方法代码示例

本文整理汇总了Python中facebookads.api.FacebookAdsApi.init方法的典型用法代码示例。如果您正苦于以下问题:Python FacebookAdsApi.init方法的具体用法?Python FacebookAdsApi.init怎么用?Python FacebookAdsApi.init使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在facebookads.api.FacebookAdsApi的用法示例。


在下文中一共展示了FacebookAdsApi.init方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: data

# 需要导入模块: from facebookads.api import FacebookAdsApi [as 别名]
# 或者: from facebookads.api.FacebookAdsApi import init [as 别名]
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)
开发者ID:prwelber,项目名称:django_fbook,代码行数:35,代码来源:views.py

示例2: __init__

# 需要导入模块: from facebookads.api import FacebookAdsApi [as 别名]
# 或者: from facebookads.api.FacebookAdsApi import init [as 别名]
		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()
开发者ID:prarthanabhattarai,项目名称:AdReportProject,代码行数:9,代码来源:getdata.py

示例3: request_new_fb_pixel

# 需要导入模块: from facebookads.api import FacebookAdsApi [as 别名]
# 或者: from facebookads.api.FacebookAdsApi import init [as 别名]
        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")
开发者ID:frecar,项目名称:epguides-api,代码行数:16,代码来源:metrics.py

示例4: get_fb_accounts

# 需要导入模块: from facebookads.api import FacebookAdsApi [as 别名]
# 或者: from facebookads.api.FacebookAdsApi import init [as 别名]
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()
开发者ID:zacharygking,项目名称:AdDashboard,代码行数:49,代码来源:views.py

示例5: auth

# 需要导入模块: from facebookads.api import FacebookAdsApi [as 别名]
# 或者: from facebookads.api.FacebookAdsApi import init [as 别名]
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"
        )
开发者ID:Jfeng3,项目名称:facebook-python-ads-sdk,代码行数:19,代码来源:bootstrap.py

示例6: facebookMain

# 需要导入模块: from facebookads.api import FacebookAdsApi [as 别名]
# 或者: from facebookads.api.FacebookAdsApi import init [as 别名]
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
开发者ID:assafdk,项目名称:RemarkIt,代码行数:22,代码来源:fbPushEmails.py

示例7: generate_record

# 需要导入模块: from facebookads.api import FacebookAdsApi [as 别名]
# 或者: from facebookads.api.FacebookAdsApi import init [as 别名]
 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']})
开发者ID:phuctoantruong,项目名称:E-marketing,代码行数:24,代码来源:facebook_ads_model.py

示例8: auth

# 需要导入模块: from facebookads.api import FacebookAdsApi [as 别名]
# 或者: from facebookads.api.FacebookAdsApi import init [as 别名]
    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),
                )
            )
开发者ID:Evzdrop,项目名称:facebook-python-ads-sdk,代码行数:39,代码来源:bootstrap.py

示例9:

# 需要导入模块: from facebookads.api import FacebookAdsApi [as 别名]
# 或者: from facebookads.api.FacebookAdsApi import init [as 别名]
from facebookads.api import FacebookAdsApi
from facebookads.objects import AdUser, Campaign, AdAccount, AdSet
from facebookads import FacebookSession, FacebookAdsApi, objects
import os

my_app_id = os.environ['APP_ID']
my_app_secret = os.environ['APP_SECRET']
my_access_token = 'CAAN4vFUE2ZAgBAHaZA6dmP6v4eIxOcV8TtA2crGjLG47ZCEllpjUSUlGFGDIFCX0KQrWBw8OGY9I7vi087ekgpaoldSyaya3HtIJgzC7oR2GQnpE8TfWi8uAB7LqtjMGqtgmvzFXZBTytZCkMDVm9WTC9vBqQZAuxVpj10yyQZC0WigZBaxvKfvG' #Your user access token
FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token)

"""
17
University of Louisville
id num: act_1006561952727232
18
Ruffino Canada
id num: act_999404050109689
19
Damp Rid
id num: act_946663412050420
20
Stoli Canada
id num: act_971018509614910
21
Beau tea Bar
id num: act_916124548437640
22
Pop Crush
id num: act_933960369987391
23
Ravage
开发者ID:prwelber,项目名称:fb_marketing_api_practice,代码行数:33,代码来源:adsets_practice.py

示例10: AdSet

# 需要导入模块: from facebookads.api import FacebookAdsApi [as 别名]
# 或者: from facebookads.api.FacebookAdsApi import init [as 别名]
# Policies [http://developers.facebook.com/policy/]. This copyright notice
# shall be included in all copies or substantial portions of the software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.

from facebookads.adobjects.adset import AdSet
from facebookads.adobjects.adsinsights import AdsInsights
from facebookads.api import FacebookAdsApi

access_token = '<ACCESS_TOKEN>'
app_secret = '<APP_SECRET>'
app_id = '<APP_ID>'
id = '<ID>'
FacebookAdsApi.init(access_token=access_token)

fields = [
  'impressions',
]
params = {
  'breakdown': 'publisher_platform',
}
print AdSet(id).get_insights(
  fields=fields,
  params=params,
)
开发者ID:Work4Labs,项目名称:facebook-python-ads-sdk,代码行数:33,代码来源:AdsInsightsEdgeAdCampaignInsights.py

示例11: open

# 需要导入模块: from facebookads.api import FacebookAdsApi [as 别名]
# 或者: from facebookads.api.FacebookAdsApi import init [as 别名]
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
开发者ID:FlagshipPromotions,项目名称:facebook-python-ads-sdk,代码行数:33,代码来源:targetsearch.py

示例12: open

# 需要导入模块: from facebookads.api import FacebookAdsApi [as 别名]
# 或者: from facebookads.api.FacebookAdsApi import init [as 别名]
repo_dir = os.path.join(this_dir, os.pardir)
sys.path.insert(1, repo_dir)

from facebookads.objects import AdAccount, AsyncJob
from facebookads.api import FacebookAdsApi
import time
import os
import json

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()

api = FacebookAdsApi.init(access_token=config['access_token'])
account_id = config['act_id']

account = AdAccount(account_id)

# Both Insights and Reportstats
i_async_job = account.get_insights(params={'level': 'ad'}, async=True)

# Insights
while True:
    job = i_async_job.remote_read()
    print("Percent done: " + str(job[AsyncJob.Field.async_percent_completion]))
    time.sleep(1)
    if job:
        # print "Done!"
        break
开发者ID:mathemads,项目名称:facebook-python-ads-sdk,代码行数:33,代码来源:async.py

示例13: open

# 需要导入模块: from facebookads.api import FacebookAdsApi [as 别名]
# 或者: from facebookads.api.FacebookAdsApi import init [as 别名]
this_dir = os.path.dirname(__file__)
config_filename = os.path.join(this_dir, os.pardir, os.pardir, 'config.json')

import sys
sys.path.insert(1, os.path.join(this_dir, os.pardir, os.pardir))

config_file = open(config_filename)
config = json.load(config_file)
config_file.close()

from facebookads.api import FacebookAdsApi
from facebookads.objects import ProductCatalog, Product

FacebookAdsApi.init(
    config['app_id'],
    config['app_secret'],
    config['access_token'],
)

if __name__ == '__main__':
    catalog_id = '<INSERT_YOUR_CATALOG_ID_HERE>'
    catalog = ProductCatalog(catalog_id)

    items = []
    for line in sys.stdin.readlines():
        if line.endswith('\n'):
            items.append(line[:-1].split(','))
        else:
            items.append(line.split(','))

    for item in items:
开发者ID:Evzdrop,项目名称:facebook-python-ads-sdk,代码行数:33,代码来源:dpa_update.py

示例14: User

# 需要导入模块: from facebookads.api import FacebookAdsApi [as 别名]
# 或者: from facebookads.api.FacebookAdsApi import init [as 别名]
from facebookads.adobjects.user import User
from facebookads.adobjects.page import Page
from facebookads.adobjects.pagepost import PagePost
from facebookads.adobjects.adaccount import AdAccount
from facebookads.adobjects.campaign import Campaign
from facebookads.adobjects.adset import AdSet
from facebookads.adobjects.adcreative import AdCreative
from facebookads.adobjects.ad import Ad
from facebookads.api import FacebookAdsApi

access_token = '<ACCESS_TOKEN>'
app_secret = '<APP_SECRET>'
app_id = '<APP_ID>'
id = '<ID>'
FacebookAdsApi.init(access_token=access_token)

# User get
fields = [
]
params = {
}
user = User(id).get(
  fields=fields,
  params=params,
)
print 'user', user
user_id = user.get_id()
print 'user_id:', user_id, '\n'

# Get page access token and page_id
开发者ID:Work4Labs,项目名称:facebook-python-ads-sdk,代码行数:32,代码来源:MultiPromoteYourPage.py

示例15: month_fb_data

# 需要导入模块: from facebookads.api import FacebookAdsApi [as 别名]
# 或者: from facebookads.api.FacebookAdsApi import init [as 别名]
def month_fb_data(request, account_model):

	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 account_model.account_name == str(current_account[AdAccount.Field.name]):
			break
		
	ad_campaigns = current_account.get_ad_campaigns()
				
	for current_campaign in ad_campaigns:
		
		fields=[
			AdCampaign.Field.name,
    		AdCampaign.Field.status,
    		AdCampaign.Field.id]
				
		params = {
			'date_preset': 'last_30_days'
		}	
		
		try:
			current_campaign.remote_read(fields=fields, params=params)
		except:
			pass
			
		fields = {    			
    		'impressions',
    		'clicks',
		'spend'
    	}
		try:
			data = str(current_campaign.get_insights(fields=fields,params=params))
		except:
			pass
		data = '['+data[12:]
		try:
			ast.literal_eval(data)
			json_string = json.dumps(data)
			parsed_data = json.loads(data)				
		except:
			continue
			
		campaign_model = FacebookCampaign()
		campaign_model.name = str(current_campaign[AdCampaign.Field.name])
		campaign_model.campaign_id = str(current_campaign[AdCampaign.Field.id])
		campaign_model.status = str(current_campaign[AdCampaign.Field.status])
		campaign_model.clicks = int(parsed_data[0]['clicks'])
		campaign_model.impressions = int(parsed_data[0]['impressions'])
		campaign_model.cost = float(parsed_data[0]['spend'])
		if not campaign_model.impressions == 0:
			campaign_model.CTR = round(campaign_model.clicks * 100/campaign_model.impressions,2)
			campaign_model.CPM = round(campaign_model.cost * 1000 / campaign_model.impressions,2)
		if not campaign_model.clicks == 0:
			campaign_model.CPC = round(campaign_model.cost/campaign_model.clicks,2)
		campaign_model.account = account_model
		campaign_model.save()	
开发者ID:zacharygking,项目名称:AdDashboard,代码行数:94,代码来源:views.py


注:本文中的facebookads.api.FacebookAdsApi.init方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。