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

4

6

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?

Shows answered 3/10, 2016 at 15:25 Comment(0)
L
4

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.

Lainelainey answered 16/5, 2017 at 20:32 Comment(0)
C
2
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)
Cutting answered 21/3, 2019 at 17:46 Comment(0)
B
2

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))
Belgravia answered 30/12, 2019 at 13:2 Comment(0)
O
0

Assuming that your response is a variable res, you can do res.headers() now.

print(json.dumps(dict(res.headers()),indent=4))
Occident answered 15/12, 2022 at 14:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.