Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Facebook Ads Python: How to access the HTTP header returned?

I want to get the load limit of my facebook ads app. I am using the facebook ads python library. According to the docs, the HTTP response contains a X-FB-Ads-Insights-Throttle header. How can I access it?

like image 350
Eadan Fahey Avatar asked Oct 03 '16 15:10

Eadan Fahey


3 Answers

import logging
import requests as rq

#Function to find the string between two strings or characters
def find_between( s, first, last ):
    try:
        start = s.index( first ) + len( first )
        end = s.index( last, start )
        return s[start:end]
    except ValueError:
        return ""

#Function to check how close you are to the FB Rate Limit
def check_limit():
    check=rq.get('https://graph.facebook.com/v3.3/act_'+account_number+'/insights?access_token='+my_access_token)
    call=float(find_between(check.headers['x-business-use-case-usage'],'call_count":','}'))
    cpu=float(find_between(check.headers['x-business-use-case-usage'],'total_cputime":','}'))
    total=float(find_between(check.headers['x-business-use-case-usage'],'total_time":',','))
    usage=max(call,cpu,total)
    return usage

#Check if you reached 75% of the limit, if yes then back-off for 5 minutes (put this chunk in your loop, every 200-500 iterations)
if (check_limit()>75):
    print('75% Rate Limit Reached. Cooling Time 5 Minutes.')
    logging.debug('75% Rate Limit Reached. Cooling Time 5 Minutes.')
    time.sleep(300)
like image 32
Ashish Baid Avatar answered Sep 24 '22 01:09

Ashish Baid


Using the python library, it won't be easily available. HTTP requests/responses are wrapped in the library to expose only minimal and necessary data.

If you're into hacking out an actual answer, look into the facebookads library source code, and look for when a FacebookResponse object is created. api.py is a file that does this for example. The FacebookResponse object contains a header attribute which will contain the X-FB-Ads-Insights-Throttle field.

If you're not into hacking into the facebookads library source code, you can use the python "Requests" library to make the http requests, and the response objects from this library will contain the header attribute you care about.

like image 144
Willy Nojopranoto Avatar answered Sep 26 '22 01:09

Willy Nojopranoto


You can access the http response headers as follows:

fbSession = FacebookSession(access_token=accessToken)
fbSession.requests.hooks['response'].append(print_headers)
// continue to make the request

def print_headers(response, *args, **kwargs):
   print(str(response.headers))
like image 44
Gary H Avatar answered Sep 27 '22 01:09

Gary H