-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy path05_custom_http_client_async.py
More file actions
58 lines (44 loc) · 1.41 KB
/
05_custom_http_client_async.py
File metadata and controls
58 lines (44 loc) · 1.41 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
from __future__ import annotations
import asyncio
from typing import Any
import httpx
from apify_client import ApifyClientAsync, HttpClientAsync, HttpResponse, Timeout
TOKEN = 'MY-APIFY-TOKEN'
class HttpxClientAsync(HttpClientAsync):
"""Custom async HTTP client using HTTPX library."""
def __init__(self) -> None:
super().__init__()
self._client = httpx.AsyncClient()
async def call(
self,
*,
method: str,
url: str,
headers: dict[str, str] | None = None,
params: dict[str, Any] | None = None,
data: str | bytes | bytearray | None = None,
json: Any = None,
stream: bool | None = None,
timeout: Timeout = 'medium',
) -> HttpResponse:
timeout_secs = self._compute_timeout(timeout, attempt=1) or 0
# httpx.Response satisfies the HttpResponse protocol,
# so it can be returned directly.
return await self._client.request(
method=method,
url=url,
headers=headers,
params=params,
content=data,
json=json,
timeout=timeout_secs,
)
async def main() -> None:
client = ApifyClientAsync.with_custom_http_client(
token=TOKEN,
http_client=HttpxClientAsync(),
)
actor = await client.actor('apify/hello-world').get()
print(actor)
if __name__ == '__main__':
asyncio.run(main())