File size: 2,118 Bytes
fc0b00d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 | """Quick test: read/write API keys to GitHub Gist.
Usage: GITHUB_TOKEN=xxx GIST_ID=yyy python test_gist.py
"""
import httpx
import json
import os
import time
TOKEN = os.environ.get("GITHUB_TOKEN", "")
GIST_ID = os.environ.get("GIST_ID", "")
if not TOKEN or not GIST_ID:
print("β Set GITHUB_TOKEN and GIST_ID environment variables first.")
print(" GITHUB_TOKEN=xxx GIST_ID=yyy python test_gist.py")
exit(1)
print(f"π Token: {TOKEN[:8]}...{TOKEN[-4:]}")
print(f"π Gist ID: {GIST_ID}")
print()
# 1. Read current keys
print("ββ Reading Gist... ββ")
resp = httpx.get(
f"https://api.github.com/gists/{GIST_ID}",
headers={"Authorization": f"Bearer {TOKEN}"},
timeout=10,
)
print(f"Status: {resp.status_code}")
if resp.status_code != 200:
print(f"β Failed: {resp.text}")
exit(1)
gist = resp.json()
content = gist.get("files", {}).get("api_keys.json", {}).get("content", "{}")
keys = json.loads(content)
print(f"β
Found {len(keys)} existing key(s)")
for k, v in keys.items():
print(f" {k} β IP: {v.get('ip')}, RPM: {v.get('rpm')}")
print()
# 2. Write a test key
test_key = f"test-{int(time.time())}"
keys[test_key] = {
"ip": "127.0.0.1",
"created": int(time.time()),
"rpm": 6,
"note": "test entry β delete me",
}
print(f"ββ Writing test key: {test_key} ββ")
resp = httpx.patch(
f"https://api.github.com/gists/{GIST_ID}",
headers={
"Authorization": f"Bearer {TOKEN}",
"Content-Type": "application/json",
},
json={"files": {"api_keys.json": {"content": json.dumps(keys, indent=2)}}},
timeout=10,
)
print(f"Status: {resp.status_code}")
if resp.status_code == 200:
print("β
Write successful!")
# Clean up test key
del keys[test_key]
httpx.patch(
f"https://api.github.com/gists/{GIST_ID}",
headers={"Authorization": f"Bearer {TOKEN}", "Content-Type": "application/json"},
json={"files": {"api_keys.json": {"content": json.dumps(keys, indent=2)}}},
timeout=10,
)
print("π§Ή Test key cleaned up.")
else:
print(f"β Failed: {resp.text}")
|