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?
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)
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.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With