To handle pagination and avoid rate limits when retrieving large sets of audiences, use the @Utils.load_all_categories decorator. This decorator automates the process of following nextToken tokens to fetch all pages.
Decorator Options:
throttle_by_seconds: The number of seconds to wait between requests to prevent throttling.next_token_param: The name of the parameter used for pagination (typically "nextToken").
When using this decorator, the decorated function becomes a generator that yields response pages.
import logging
from ad_api.api import Audiences
from ad_api.base import AdvertisingApiException, Utils
@Utils.load_all_categories(throttle_by_seconds=5, next_token_param="nextToken")
def get_all_categories(**kwargs):
return Audiences(debug=True).list_audiences(**kwargs)
if __name__ == '__main__':
request = {
"adType": "SD",
}
for page in get_all_categories(maxResults=20, body=request):
result = page.payload
audiences = result.get("audiences")
for audience in audiences:
logging.info(audience)