xdevplatform / twitter-python-ads-sdk

A Twitter supported and maintained Ads API SDK for Python.
https://twitterdev.github.io/twitter-python-ads-sdk/
MIT License
189 stars 106 forks source link

handle rate limit and implement retry logic #213

Closed smaeda-ks closed 5 years ago

smaeda-ks commented 5 years ago

Adding rate limit handling and retry logic.

Usage

client = Client( CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET, options={ 'handle_rate_limit': True # default is False })

account = Account.load(client, ACCOUNT_ID) campaigns = Campaign.all(account)


- retry
```py
client = Client(
    CONSUMER_KEY,
    CONSUMER_SECRET,
    ACCESS_TOKEN,
    ACCESS_TOKEN_SECRET,
    options={
        'retry_max': 3,  # default is 0
        'retry_delay': 5000,  # milliseconds (default is 1500)
        'retry_on_status': [404, 500, 503]  # status codes you want to retry on
    })

account = Account.load(client, ACCOUNT_ID)
campaigns = Campaign.all(account)

account = Account.load(client, ACCOUNT_ID) campaigns = Campaign.all(account)


### Test with actual requests
- code
```py
client = Client(
    CONSUMER_KEY,
    CONSUMER_SECRET,
    ACCESS_TOKEN,
    ACCESS_TOKEN_SECRET,
    options={
        'handle_rate_limit': True,
        'retry_max': 3,
        'retry_delay': 5000,
        'retry_on_status': [404, 500, 503]
    })

account = client.accounts(ACCOUNT_ID)

data = TargetingCriteria.locations(account, count=1)

for i in data:
    print(i['targeting_value'])
    print("rate_limit_remaining: {}".format(data.rate_limit_remaining))

10c4b91189877846 rate_limit_remaining: 399 f6069e863e29e322 rate_limit_remaining: 398 84e681a9fb76656f rate_limit_remaining: 397 03ee27c08cf99bea rate_limit_remaining: 396 f39bb92424252cee rate_limit_remaining: 395 8f88713a5e8554ff