Facebook Marketing API - Python to get Insights - User Request Limit Reached

前端 未结 3 1958
一向
一向 2020-12-05 16:40

So I am trying my best to navigate my way through the Facebook API. I need to crate a script that will download my business\' campaign information daily as a csv file so I c

3条回答
  •  情深已故
    2020-12-05 17:10

    Adding a couple of small functions to improve on LucyTurtle's answer as it is still susceptible to Facebook's Rate Limiting

    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():
        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 'for ad is ads' loop, every 100-200 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)
    

提交回复
热议问题