-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdevto_proxy.py
More file actions
83 lines (77 loc) · 3.19 KB
/
Copy pathdevto_proxy.py
File metadata and controls
83 lines (77 loc) · 3.19 KB
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
77
78
79
80
81
82
83
#!/usr/bin/env python3
"""
devto_proxy.py — local proxy for dev.to analytics
Adds the api-key header server-side, bypassing browser CORS restrictions.
Usage: DEVTO_API_KEY=your_key python3 devto_proxy.py
Then open http://localhost:8765/devto_analytics.html
"""
import sys
import json
import urllib.request
import urllib.error
from http.server import HTTPServer, BaseHTTPRequestHandler
from pathlib import Path
import os
API_KEY = os.environ.get("DEVTO_API_KEY", "")
SERVE_DIR = Path(__file__).parent
PORT = 8765
class Handler(BaseHTTPRequestHandler):
def log_message(self, fmt, *args):
print(f" {self.address_string()} {fmt % args}")
def do_GET(self):
if self.path == '/':
self.path = '/devto_analytics.html'
# Proxy /api/* to dev.to with the api-key header
if self.path.startswith("/api/"):
devto_url = "https://dev.to" + self.path
req = urllib.request.Request(devto_url, headers={
"api-key": API_KEY,
"Accept": "application/json",
"User-Agent": "devto-analytics-proxy/1.0",
})
try:
with urllib.request.urlopen(req, timeout=15) as resp:
body = resp.read()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Access-Control-Allow-Origin", "*")
self.end_headers()
self.wfile.write(body)
except urllib.error.HTTPError as e:
body = e.read()
self.send_response(e.code)
self.send_header("Content-Type", "application/json")
self.send_header("Access-Control-Allow-Origin", "*")
self.end_headers()
self.wfile.write(body)
except Exception as e:
self.send_response(502)
self.end_headers()
self.wfile.write(json.dumps({"error": str(e)}).encode())
return
# Serve static files from the same directory
file_path = SERVE_DIR / self.path.lstrip("/")
if self.path == "/" or not file_path.exists():
file_path = SERVE_DIR / "devto_analytics.html"
if file_path.exists() and file_path.is_file():
suffix = file_path.suffix.lower()
ctype = {"html": "text/html", "js": "text/javascript", "css": "text/css"}.get(suffix[1:], "text/plain")
self.send_response(200)
self.send_header("Content-Type", ctype)
self.end_headers()
self.wfile.write(file_path.read_bytes())
else:
self.send_response(404)
self.end_headers()
def do_OPTIONS(self):
self.send_response(200)
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Access-Control-Allow-Headers", "*")
self.end_headers()
if __name__ == "__main__":
if not API_KEY:
print("usage: python3 devto_proxy.py YOUR_DEV_TO_API_KEY")
sys.exit(1)
print(f"proxy running → http://localhost:{PORT}/devto_analytics.html")
print(f"api key: {API_KEY[:6]}{'*' * (len(API_KEY)-6)}")
HTTPServer(("", PORT), Handler).serve_forever()