Ejemplo n.º 1
0
def reset_thread_state(**kwargs):
    '''
    Called to reset static variables for example the API instance after we are
    done with one request to prevent them from unintentionally lingering between
    requests.
    '''
    FacebookAdsApi.set_default_api(None)
Ejemplo n.º 2
0
def campaigns_with_insights(start, end):
    response = []
    try:
        my_session = FacebookSession(my_app_id, my_app_secret, my_access_token)
        my_api = FacebookAdsApi(my_session)
        FacebookAdsApi.set_default_api(my_api)
        me = objects.AdUser(fbid='me')
        my_accounts = list(me.get_ad_accounts())
        my_account = my_accounts[0]
        fields = [
            AdsInsights.Field.clicks, AdsInsights.Field.spend,
            AdsInsights.Field.impressions, AdsInsights.Field.unique_clicks,
            AdsInsights.Field.cost_per_unique_click,
            AdsInsights.Field.cost_per_inline_link_click
        ]

        params = {
            'time_range': {
                'since': start,
                'until': end
            },
            'effective_status': ["ACTIVE"]
        }
        campaigns = my_account.get_campaigns(
            params=params, fields=[Campaign.Field.name, Campaign.Field.status])
        headers = [
            "Name",
            'Cost',
            "Impressions",
            "Clicks",
            "Unique Clicks",
            "Cost per unique click",
        ]
        for i in campaigns:
            try:
                campaign = Campaign(i['id'])
                campaign_data = campaign.get_insights(params=params,
                                                      fields=fields)
                campaign_dict = {
                    'id':
                    i['id'],
                    'name':
                    i['name'],
                    'Cost':
                    campaign_data[0]['spend'],
                    "Clicks":
                    campaign_data[0]['clicks'],
                    "Unique_Clicks":
                    campaign_data[0]['unique_clicks'],
                    "Cost_per_unique_click":
                    campaign_data[0]['cost_per_unique_click'],
                    "Impressions":
                    campaign_data[0]['impressions']
                }
                response.append(campaign_dict)
            except:
                pass
    except:
        pass
    return {'headers': headers, 'rows': response}
Ejemplo n.º 3
0
Archivo: main.py Proyecto: Peridian/etl
def facebook_get_service(config):
    '''
    Connects to Facebook Ads platform
    '''
    session = FacebookSession(config['app_id'], config['app_secret'],
                              config['access_token'])
    api = FacebookAdsApi(session)
    FacebookAdsApi.set_default_api(api)
    FacebookAdsApi.init(config['app_id'], config['app_secret'],
                        config['access_token'])
Ejemplo n.º 4
0
    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)
Ejemplo n.º 5
0
def insights(start, end):
    response = {}
    try:
        my_session = FacebookSession(my_app_id, my_app_secret, my_access_token)
        my_api = FacebookAdsApi(my_session)
        FacebookAdsApi.set_default_api(my_api)
        me = objects.AdUser(fbid='me')
        my_accounts = list(me.get_ad_accounts())
        my_account = my_accounts[0]
        fields = [
            AdsInsights.Field.clicks, AdsInsights.Field.spend,
            AdsInsights.Field.impressions, AdsInsights.Field.unique_clicks,
            AdsInsights.Field.cost_per_unique_click,
            AdsInsights.Field.cost_per_inline_link_click
        ]

        params = {
            'time_range': {
                'since': start,
                'until': end
            },
        }
        temp = my_account.get_insights(params=params, fields=fields)

        try:
            cost_per_click = float(temp[0]['spend']) / float(temp[0]['clicks'])
        except:
            cost_per_click = 0

        response = [{
            'field': 'Impressions',
            'value': temp[0]['impressions']
        }, {
            'field': 'Cost',
            'value': temp[0]['spend']
        }, {
            'field': 'Clicks',
            'value': temp[0]['clicks']
        }, {
            'field': 'Unique Clicks',
            'value': temp[0]['unique_clicks']
        }, {
            'field': 'Cost per unique click',
            'value': temp[0]['cost_per_unique_click']
        }, {
            'field': 'Cost per Click',
            'value': cost_per_click
        }]
    except:
        pass

    return response
Ejemplo n.º 6
0
    def setUp(self):
        fbads_session = FacebookSession(
            settings.SAMPLE_TEST['APP_ID'],
            settings.SAMPLE_TEST['APP_SECRET'],
            settings.SAMPLE_TEST['TOKEN'],
        )
        fbads_api = FacebookAdsApi(fbads_session)
        FacebookAdsApi.set_default_api(fbads_api)
        self.account_id = settings.SAMPLE_TEST['ACCOUNT_ID']
        self.page_id = settings.SAMPLE_TEST['PAGE_ID']
        self.form_id = '436706799859690'  # For Lead Ads
        image_files = [
            "adimage0.png", "adimage1.jpg", "adimage2.jpg", "adimage3.jpg"
        ]

        self.images = map(
            lambda image_path: os.path.abspath(
                os.path.join(os.path.dirname(__file__), image_path)),
            image_files)
        self.app_info = {
            "app_name": "DiDiAds",
            "appstore_link":
            "https://play.google.com/store/apps/details?id=com.facebook.se.apac.example.liyuhk.didiadsa",
            "app_deep_link": "example://detail/1234",
            "fbapplication_id": "743337925789686",
            "fbpage_id": "1426815194312958",
            "fboffsitepixel_id": "null"
        }
        self.basic_targeting = {
            "geo_locations": {
                "countries": ["US"]
            },
        }

        self.mobile_targeting = {
            "geo_locations": {
                "countries": ["US"]
            },
            "user_os": ["Android"],
            "device_platforms": ["mobile"],
            "publisher_platforms": ["facebook"],
            "facebook_positions": ["feed"],
        }
        # Base custom audience id that can be used for creating LALs etc.
        self.ca_id = "6034234313285"
Ejemplo n.º 7
0
    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)
Ejemplo n.º 8
0
def get_session_user(request):
    user = None
    # check the userid and access token in the session
    # if exists get the user and install on the request
    # if not exists, redirect to login page with next
    fb_userid = request.session.get('fbuserid', None)
    token = request.session.get('token', None)
    if (fb_userid is not None and token is not None):
        logger.debug("Found fb_userid in session. Getting User object")
        user = FBAuthBackend().get_user(fb_userid)
        if user is not None:
            logger.debug("Got the User object")
            # TODO we should move these lines to the sample code
            # to make samples more self-contained
            fbads_session = FacebookSession(
                settings.FACEBOOK_APP_ID,
                settings.FACEBOOK_APP_SECRET,
                token)
            fbads_api = FacebookAdsApi(fbads_session)

            # Set the user agent for the API requests from default
            # "fb-python-ads-api-sdk-%s" % SDK_VERSION, to
            # "fb-python-ads-muse-%s" % SDK_VERSION,
            fbads_api.HTTP_DEFAULT_HEADERS['User-Agent'] = \
                "fb-python-ads-muse-" + fbads_api.SDK_VERSION

            FacebookAdsApi.set_default_api(fbads_api)
            request.fbads_api = fbads_api
            logger.debug("Added fbads_api to request")
        else:
            logger.info("The fb_userid in session did not map to a valid user.")
            clear_session_user(request)
    else:
        logger.debug("fb_userid and/or token not found in session")
        FacebookAdsApi.set_default_api(None)

    return user
Ejemplo n.º 9
0
sys.path.insert(1, sdk_path)

config_filename = os.path.join(sdk_path, '.credentials/facebook.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'],
)

FacebookAdsApi.set_default_api(FacebookAdsApi(session))

if __name__ == '__main__':
    business = Business('1628260363868706')
    ad_accounts = list(business.get_owned_ad_accounts())
    print ad_accounts

    # # create video object
    # video = AdVideo(parent_id=config['act_id'])

    # video_path = os.path.join(
    #     os.path.dirname(__file__),
    #     'test.mov'
    #     #'sample.mp4'
    # )
    #
Ejemplo n.º 10
0
	def __init__(self):
		session = FacebookSession(fb_app_id, fb_app_secret, fb_extended_token)
		api = FacebookAdsApi(session)
		FacebookAdsApi.set_default_api(api)
		self.me = User(fbid='me')
		self.getAccounts()
Ejemplo n.º 11
0
from facebookads.session import FacebookSession
from facebookads.api import FacebookAdsApi
from facebookads import objects
from facebookads.objects import AdUser, AdCampaign
import os

my_app_id = os.environ.get('FB_APP_ID')
my_app_secret = os.environ.get('FB_SECRET_KEY')
my_access_token = os.environ.get('FB_ACCESS_TOKEN')
my_session = FacebookSession(my_app_id, my_app_secret, my_access_token)
my_api = FacebookAdsApi(my_session)
FacebookAdsApi.set_default_api(my_api)

me = objects.AdUser(fbid='me')
my_accounts = list(me.get_ad_accounts())

my_account = my_accounts[1]

print(">>> Campaign Stats")
for campaign in my_account.get_ad_campaigns(fields=[AdCampaign.Field.name]):
    for stat in campaign.get_stats(fields=[
            'impressions',
            'clicks',
            'spent',
            'unique_clicks',
            'actions',
    ]):
        print(campaign[campaign.Field.name])
    for statfield in stat:
        print("\t%s:\t\t%s" % (statfield, stat[statfield]))
Ejemplo n.º 12
0
def clear_session_user(request):
    rotate_token(request)
    request.session.flush()
    FacebookAdsApi.set_default_api(None)
Ejemplo n.º 13
0
config_file = open(config_filename)
config = json.load(config_file)

DAVE = 0
ABACUS = 4

my_app_id = config['app_id']
my_app_secret = config['app_secret']
my_access_token_1 = config['access_token']

session1 = FacebookSession(my_app_id, my_app_secret, my_access_token_1)

api1 = FacebookAdsApi(session1)

FacebookAdsApi.set_default_api(api1)
me = User(fbid='me', api=api1)
my_accounts = list(me.get_ad_accounts())
print(my_accounts)
my_account = my_accounts[ABACUS]

my_account_id = my_account.get_id_assured()
print(my_account_id)

account = AdAccount(my_account_id)
custom_audiences = account.get_custom_audiences(fields=[
    CustomAudience.Field.name, CustomAudience.Field.id,
    CustomAudience.Field.approximate_count
])

our_audiences = []