(url, token, retries=1)
| 52 | |
| 53 | |
| 54 | def request_json(url, token, retries=1): |
| 55 | req = Request(url) |
| 56 | req.add_header("Authorization", f"Bearer {token}") |
| 57 | req.add_header("Accept", "application/json") |
| 58 | |
| 59 | attempt = 0 |
| 60 | while True: |
| 61 | try: |
| 62 | with urlopen(req) as resp: |
| 63 | body = resp.read().decode("utf-8") |
| 64 | data = json.loads(body) if body else None |
| 65 | return data, resp.headers |
| 66 | except HTTPError as err: |
| 67 | body = err.read().decode("utf-8", "ignore") |
| 68 | if attempt < retries and (err.code >= 500 or err.code == 429): |
| 69 | attempt += 1 |
| 70 | time.sleep(1) |
| 71 | continue |
| 72 | raise RuntimeError(f"HTTP {err.code} for {url}: {body or 'request failed'}") from err |
| 73 | except URLError as err: |
| 74 | if attempt < retries: |
| 75 | attempt += 1 |
| 76 | time.sleep(1) |
| 77 | continue |
| 78 | raise RuntimeError(f"Network error for {url}: {err.reason}") from err |
| 79 | |
| 80 | |
| 81 | def build_url(base_url, path, params=None): |
no test coverage detected