|
1 | 1 | import json |
| 2 | +import time |
2 | 3 |
|
3 | 4 | import requests |
4 | 5 |
|
@@ -86,29 +87,33 @@ def send_query(query, query_type, headers, cursor=None): |
86 | 87 | # Build request payload |
87 | 88 | payload = {"query": "".join(query.split("\n"))} |
88 | 89 | 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} |
90 | 92 |
|
91 | 93 |
|
92 | 94 | def get_all_responses(query, query_type, headers): |
93 | 95 | """ |
94 | 96 | Helper function to bypass GitHub GraphQL API node limit. |
95 | 97 | """ |
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 |
102 | 103 | 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) |
103 | 109 | 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) |
105 | 112 | data.extend(pdata) |
106 | 113 | print( |
107 | | - f"OK\nRetrieving {len(data)} out of {total_count} values...", |
108 | | - end="", |
| 114 | + f"OK [{len(data)}/{total_count}] [ratelimit: {ratelimit_remaining}]", |
109 | 115 | flush=True, |
110 | 116 | ) |
111 | | - print("OK") |
112 | 117 | return data |
113 | 118 |
|
114 | 119 |
|
|
0 commit comments