|
| 1 | +import httpx |
| 2 | +import requests |
| 3 | +import urllib3 |
| 4 | +from workers import Response, WorkerEntrypoint |
| 5 | + |
| 6 | +TARGET_URL = "https://example.com/" |
| 7 | +EXPECTED_TEXT = "Example Domain" |
| 8 | + |
| 9 | + |
| 10 | +def summarize_result(client, status_code, text, headers=None): |
| 11 | + """Return a small JSON-safe summary for an outbound HTTP response.""" |
| 12 | + headers = headers or {} |
| 13 | + return { |
| 14 | + "client": client, |
| 15 | + "status_code": int(status_code), |
| 16 | + "ok": 200 <= int(status_code) < 300, |
| 17 | + "saw_expected_text": EXPECTED_TEXT in text, |
| 18 | + "content_type": headers.get("content-type") or headers.get("Content-Type"), |
| 19 | + "body_preview": text[:80], |
| 20 | + } |
| 21 | + |
| 22 | + |
| 23 | +class Default(WorkerEntrypoint): |
| 24 | + async def fetch(self, request): |
| 25 | + path = request.url.split("/", 3)[-1] |
| 26 | + path = "/" + path.split("?", 1)[0] if path else "/" |
| 27 | + |
| 28 | + if path == "/": |
| 29 | + return Response.json( |
| 30 | + { |
| 31 | + "example": "Synchronous HTTP clients in Python Workers", |
| 32 | + "target": TARGET_URL, |
| 33 | + "clients": ["requests", "urllib3", "httpx.Client"], |
| 34 | + "endpoints": { |
| 35 | + "GET /sync": "Fetch using requests, urllib3, and httpx.Client", |
| 36 | + "GET /all": "Alias for /sync", |
| 37 | + }, |
| 38 | + } |
| 39 | + ) |
| 40 | + |
| 41 | + if path in ("/sync", "/all"): |
| 42 | + return Response.json({"target": TARGET_URL, "results": self.fetch_sync()}) |
| 43 | + |
| 44 | + return Response.json({"error": "not found"}, status=404) |
| 45 | + |
| 46 | + def fetch_sync(self): |
| 47 | + """Use blocking-style Python HTTP clients from a Python Worker.""" |
| 48 | + requests_response = requests.get(TARGET_URL, timeout=10) |
| 49 | + |
| 50 | + pool = urllib3.PoolManager() |
| 51 | + urllib3_response = pool.request("GET", TARGET_URL, timeout=10.0) |
| 52 | + urllib3_text = urllib3_response.data.decode("utf-8") |
| 53 | + |
| 54 | + with httpx.Client() as client: |
| 55 | + httpx_response = client.get(TARGET_URL, timeout=10.0) |
| 56 | + |
| 57 | + return [ |
| 58 | + summarize_result( |
| 59 | + "requests", |
| 60 | + requests_response.status_code, |
| 61 | + requests_response.text, |
| 62 | + requests_response.headers, |
| 63 | + ), |
| 64 | + summarize_result( |
| 65 | + "urllib3", |
| 66 | + urllib3_response.status, |
| 67 | + urllib3_text, |
| 68 | + urllib3_response.headers, |
| 69 | + ), |
| 70 | + summarize_result( |
| 71 | + "httpx.Client", |
| 72 | + httpx_response.status_code, |
| 73 | + httpx_response.text, |
| 74 | + httpx_response.headers, |
| 75 | + ), |
| 76 | + ] |
0 commit comments