Skip to content

Instantly share code, notes, and snippets.

@dltacube
Last active February 7, 2018 16:59
Show Gist options
  • Save dltacube/7e7fab644949e44828f8b0596b5b47ac to your computer and use it in GitHub Desktop.
Save dltacube/7e7fab644949e44828f8b0596b5b47ac to your computer and use it in GitHub Desktop.
example of how to rate limit your tmdb queries
import time
import requests
def query(query, collection):
URL = BASE_URL + '/' + collection + '/' + str(query['id'])
params = {'api_key': KEY}
if collection == 'tv' or collection == 'movie':
params = {
'api_key': KEY,
'language': 'en-US',
'append_to_response': 'alternative_titles,content_ratings,credits,external_ids,images',
'include_image_language': 'en,null'
}
r = requests.get(URL, params)
print('queries left: {}'.format(r.headers['X-RateLimit-Remaining']))
print('Resets at: {}'.format(r.headers['X-RateLimit-Reset']))
check_rate_limit(r)
if r.status_code == 200:
return r.json()
if r.status_code == 429:
return 429
if r.status_code == 404:
return 404
def check_rate_limit(r):
current_time = time.time()
if int(r.headers['X-RateLimit-Remaining']) <= 1:
while int(r.headers['X-RateLimit-Reset']) + 1 > time.time():
print('waiting...')
time.sleep(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment