-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcatfact_client.py
49 lines (38 loc) · 1.23 KB
/
catfact_client.py
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
import asyncio
from http import HTTPStatus
from types import MappingProxyType
from aiohttp import ClientSession, hdrs
from pydantic import BaseModel
from asyncly import DEFAULT_TIMEOUT, BaseHttpClient, ResponseHandlersType
from asyncly.client.handlers.pydantic import parse_model
from asyncly.client.timeout import TimeoutType
class CatfactSchema(BaseModel):
fact: str
length: int
class CatfactClient(BaseHttpClient):
RANDOM_CATFACT_HANDLERS: ResponseHandlersType = MappingProxyType(
{
HTTPStatus.OK: parse_model(CatfactSchema),
}
)
async def fetch_random_cat_fact(
self,
timeout: TimeoutType = DEFAULT_TIMEOUT,
) -> CatfactSchema:
return await self._make_req(
method=hdrs.METH_GET,
url=self._url / "fact",
handlers=self.RANDOM_CATFACT_HANDLERS,
timeout=timeout,
)
async def main() -> None:
async with ClientSession() as session:
client = CatfactClient(
client_name="catfact",
session=session,
url="https://catfact.ninja",
)
fact = await client.fetch_random_cat_fact()
print(fact) # noqa: T201
if __name__ == "__main__":
asyncio.run(main())