|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import sys |
| 4 | +from typing import Any, Mapping |
| 5 | + |
| 6 | +if sys.version_info < (3, 8): |
| 7 | + from typing_extensions import Protocol |
| 8 | +else: |
| 9 | + from typing import Protocol |
| 10 | + |
| 11 | +try: |
| 12 | + import requests |
| 13 | +except ImportError: |
| 14 | + requests = None |
| 15 | + |
| 16 | +try: |
| 17 | + import httpx |
| 18 | +except ImportError: |
| 19 | + httpx = None |
| 20 | + |
| 21 | +try: |
| 22 | + import aiohttp |
| 23 | +except ImportError: |
| 24 | + aiohttp = None |
| 25 | + |
| 26 | +import json |
| 27 | +import urllib.error |
| 28 | +import urllib.parse |
| 29 | +import urllib.request |
| 30 | + |
| 31 | + |
| 32 | +class HttpClient(Protocol): |
| 33 | + def get(self, url: str, params: Mapping[str, Any]) -> tuple[int, Any, Mapping[str, Any]]: ... |
| 34 | + |
| 35 | + def close(self): ... |
| 36 | + |
| 37 | + |
| 38 | +class AsyncHttpClient(Protocol): |
| 39 | + async def get( |
| 40 | + self, url: str, params: Mapping[str, Any] |
| 41 | + ) -> tuple[int, Any, Mapping[str, Any]]: ... |
| 42 | + |
| 43 | + async def close(self): ... |
| 44 | + |
| 45 | + |
| 46 | +DEFAULT_TIMEOUT = 600 |
| 47 | + |
| 48 | + |
| 49 | +def default_async_client(timeout: int = DEFAULT_TIMEOUT): |
| 50 | + if httpx: |
| 51 | + print("HttpxAsyncClient") |
| 52 | + return HttpxAsyncClient(timeout=timeout) |
| 53 | + if aiohttp: |
| 54 | + print("AioHttpClient") |
| 55 | + return AioHttpClient(timeout=timeout) |
| 56 | + |
| 57 | + raise ImportError( |
| 58 | + "No async HTTP client available. To use async please make sure to install" |
| 59 | + " either httpx or aiohttp. Alternatively, you can implement your own version of the" |
| 60 | + " AsyncHttpClient protocol." |
| 61 | + ) |
| 62 | + |
| 63 | + |
| 64 | +def default_sync_client(timeout: int = DEFAULT_TIMEOUT): |
| 65 | + if httpx: |
| 66 | + print("HttpxClient") |
| 67 | + return HttpxClient(timeout=timeout) |
| 68 | + if requests: |
| 69 | + print("RequestsClient") |
| 70 | + return RequestsClient(timeout=timeout) |
| 71 | + |
| 72 | + print("UrllibClient") |
| 73 | + return UrllibClient() |
| 74 | + |
| 75 | + |
| 76 | +class UrllibClient(HttpClient): |
| 77 | + def __init__(self, timeout: int = DEFAULT_TIMEOUT): |
| 78 | + self._timeout = timeout |
| 79 | + |
| 80 | + def get(self, url: str, params: Mapping[str, Any]): |
| 81 | + url += "?" + urllib.parse.urlencode(params, doseq=True, safe="/") |
| 82 | + req = urllib.request.Request(url, method="GET", headers={}) |
| 83 | + |
| 84 | + try: |
| 85 | + with urllib.request.urlopen(req, timeout=self._timeout) as res: |
| 86 | + return res.status, json.loads(res.read().decode()), dict(res.headers) |
| 87 | + except urllib.error.HTTPError as e: |
| 88 | + return e.code, json.loads(e.read().decode()), dict(e.headers) |
| 89 | + |
| 90 | + def close(self): |
| 91 | + pass |
| 92 | + |
| 93 | + |
| 94 | +class RequestsClient(HttpClient): |
| 95 | + def __init__(self, timeout: int = DEFAULT_TIMEOUT): |
| 96 | + if not requests: |
| 97 | + raise ImportError("requests is not installed") |
| 98 | + self._session = requests.Session() |
| 99 | + self._timeout = timeout |
| 100 | + |
| 101 | + def get(self, url: str, params: Mapping[str, Any]): |
| 102 | + assert requests is not None |
| 103 | + res = self._session.get(url, params=params, timeout=self._timeout) |
| 104 | + return res.status_code, res.json(), res.headers |
| 105 | + |
| 106 | + def close(self): |
| 107 | + self._session.close() |
| 108 | + |
| 109 | + |
| 110 | +class HttpxClient(HttpClient): |
| 111 | + def __init__(self, timeout: int = DEFAULT_TIMEOUT): |
| 112 | + if not httpx: |
| 113 | + raise ImportError("httpx is not installed") |
| 114 | + self._client = httpx.Client(timeout=timeout) |
| 115 | + |
| 116 | + def get(self, url: str, params: Mapping[str, Any]): |
| 117 | + res = self._client.get(url, params=params) |
| 118 | + return res.status_code, res.json(), res.headers |
| 119 | + |
| 120 | + def close(self): |
| 121 | + self._client.close() |
| 122 | + |
| 123 | + |
| 124 | +class HttpxAsyncClient(AsyncHttpClient): |
| 125 | + def __init__(self, timeout: int = DEFAULT_TIMEOUT): |
| 126 | + if not httpx: |
| 127 | + raise ImportError("httpx is not installed") |
| 128 | + self._client = httpx.AsyncClient(timeout=timeout) |
| 129 | + |
| 130 | + async def get(self, url: str, params: Mapping[str, Any]): |
| 131 | + print("get httpx") |
| 132 | + res = await self._client.get(url, params=params) |
| 133 | + return res.status_code, res.json(), res.headers |
| 134 | + |
| 135 | + async def close(self): |
| 136 | + await self._client.aclose() |
| 137 | + |
| 138 | + |
| 139 | +class AioHttpClient(AsyncHttpClient): |
| 140 | + def __init__(self, timeout: int = DEFAULT_TIMEOUT): |
| 141 | + if not aiohttp: |
| 142 | + raise ImportError("aiohttp is not installed") |
| 143 | + self._client = aiohttp.ClientSession(read_timeout=timeout) |
| 144 | + |
| 145 | + async def get(self, url: str, params: Mapping[str, Any]): |
| 146 | + print("get aiohttp") |
| 147 | + async with self._client.get(url, params=params) as response: |
| 148 | + return response.status, await response.json(), response.headers |
| 149 | + |
| 150 | + async def close(self): |
| 151 | + await self._client.close() |
| 152 | + |
| 153 | + |
| 154 | +if __name__ == "__main__": |
| 155 | + client = UrllibClient() |
| 156 | + status, data, headers = client.get( |
| 157 | + "https://ensembledata.com/apis/customer/get-used-units", |
| 158 | + {"token": "mbWgvamioO7dQUJ9", "date": "2024-01-01"}, |
| 159 | + ) |
| 160 | + print(status, data, headers) |
0 commit comments