Skip to content

Commit 0d40cb5

Browse files
authored
Display rate limit when querying (#69)
1 parent 5978e8d commit 0d40cb5

File tree

1 file changed

+16
-11
lines changed

1 file changed

+16
-11
lines changed

devstats/query.py

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import json
2+
import time
23

34
import requests
45

@@ -86,29 +87,33 @@ def send_query(query, query_type, headers, cursor=None):
8687
# Build request payload
8788
payload = {"query": "".join(query.split("\n"))}
8889
response = requests.post(endpoint, json=payload, headers=headers)
89-
return json.loads(response.content)
90+
rate_limit = {h: response.headers[h] for h in ("x-ratelimit-remaining",)}
91+
return {**json.loads(response.content), **rate_limit}
9092

9193

9294
def get_all_responses(query, query_type, headers):
9395
"""
9496
Helper function to bypass GitHub GraphQL API node limit.
9597
"""
96-
# Get data from a single response
97-
print("Retrieving first page...", end="", flush=True)
98-
initial_data = send_query(query, query_type, headers)
99-
data, last_cursor, total_count = parse_single_query(initial_data, query_type)
100-
101-
# Continue requesting data (with pagination) until all are acquired
98+
data = []
99+
total_count = 1
100+
last_cursor = None
101+
rdata = {}
102+
ratelimit_remaining = 10
102103
while len(data) < total_count:
104+
if ratelimit_remaining < 10:
105+
print("Close to hitting rate limit; sleeping 30s")
106+
time.sleep(30)
107+
108+
print("Fetching...", end="", flush=True)
103109
rdata = send_query(query, query_type, headers, cursor=last_cursor)
104-
pdata, last_cursor, _ = parse_single_query(rdata, query_type)
110+
ratelimit_remaining = int(rdata["x-ratelimit-remaining"])
111+
pdata, last_cursor, total_count = parse_single_query(rdata, query_type)
105112
data.extend(pdata)
106113
print(
107-
f"OK\nRetrieving {len(data)} out of {total_count} values...",
108-
end="",
114+
f"OK [{len(data)}/{total_count}] [ratelimit: {ratelimit_remaining}]",
109115
flush=True,
110116
)
111-
print("OK")
112117
return data
113118

114119

0 commit comments

Comments
 (0)