From 2e2756db07722cabecb11375ac0c2cd071a99322 Mon Sep 17 00:00:00 2001 From: agatha Date: Fri, 10 Nov 2023 20:54:23 -0500 Subject: [PATCH] Sleep until rate limit refresh --- gitmon/api.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/gitmon/api.py b/gitmon/api.py index 04e96aa..41d3222 100644 --- a/gitmon/api.py +++ b/gitmon/api.py @@ -1,6 +1,8 @@ """GitHub API module""" import logging import requests +from datetime import datetime +from time import sleep from requests.adapters import HTTPAdapter from requests.packages.urllib3.util.retry import Retry @@ -26,6 +28,12 @@ class GitHubApi: """GET an HTTP resource and return JSON.""" url = self.base_url + endpoint + # Check rate limits + if self.rate_remaining == 0 and self.rate_reset > datetime.now(): + logging.warning(f'Out of API calls. Sleeping until {self.rate_reset}.') + delta = self.rate_reset - datetime.now() + sleep(delta.total_seconds()) + try: response = self.session.get(url, params=params) except requests.RequestException as e: @@ -41,7 +49,7 @@ class GitHubApi: def __parse_headers(self, headers): """Parse headers to update rate limits.""" - self.rate_reset = int(headers['x-ratelimit-reset']) + self.rate_reset = datetime.fromtimestamp(int(headers['x-ratelimit-reset'])) self.rate_remaining = int(headers['x-ratelimit-remaining']) def get_events(self, page=None):