|
1 | | -from fastcrawler.engine.base import EngineProto |
| 1 | +import asyncio |
2 | 2 |
|
| 3 | +import pydantic |
| 4 | +from aiohttp import BasicAuth, ClientSession, TCPConnector |
| 5 | +from aiohttp.cookiejar import Morsel |
3 | 6 |
|
4 | | -class AioHTTP(EngineProto): |
5 | | - ... |
| 7 | +from fastcrawler.engine.base import ProxySetting, SetCookieParam |
| 8 | + |
| 9 | + |
| 10 | +class AioHTTP: |
| 11 | + def __init__( |
| 12 | + self, |
| 13 | + cookies: list[SetCookieParam] | None = None, |
| 14 | + headers: dict | None = None, |
| 15 | + useragent: str | None = None, |
| 16 | + proxy: ProxySetting | None = None, |
| 17 | + connection_limit: int = 100, |
| 18 | + ): |
| 19 | + """Initialize a new engine instance with given cookie, header, useragent, and proxy""" |
| 20 | + self.session = None |
| 21 | + self._cookies = ( |
| 22 | + [(cookie.name, self.get_morsel_cookie(cookie)) for cookie in cookies] |
| 23 | + if cookies is not None |
| 24 | + else None |
| 25 | + ) |
| 26 | + |
| 27 | + self._headers = headers or {} |
| 28 | + if useragent: |
| 29 | + self._headers["User-Agent"] = useragent |
| 30 | + |
| 31 | + self._connector = TCPConnector(limit_per_host=connection_limit) |
| 32 | + |
| 33 | + self._proxy = {} |
| 34 | + if proxy: |
| 35 | + proxy_url = f"{proxy.protocol}{proxy.server}:{proxy.port}" |
| 36 | + self._proxy["proxy"] = proxy_url |
| 37 | + if proxy.username and proxy.password: |
| 38 | + auth = BasicAuth(login=proxy.username, password=proxy.password) |
| 39 | + self._proxy["proxy_auth"] = auth |
| 40 | + |
| 41 | + @property |
| 42 | + def cookies(self): |
| 43 | + return self._cookies |
| 44 | + |
| 45 | + @property |
| 46 | + def headers(self): |
| 47 | + return self._headers |
| 48 | + |
| 49 | + @property |
| 50 | + def proxy(self): |
| 51 | + return self._proxy |
| 52 | + |
| 53 | + def get_morsel_cookie(self, cookie: SetCookieParam) -> Morsel: |
| 54 | + """Converts a SetCookieParam object to an Morsel object.""" |
| 55 | + morsel_obj = Morsel() |
| 56 | + morsel_obj.set(cookie.name, cookie.value, cookie.value) |
| 57 | + morsel_obj.update( |
| 58 | + dict( |
| 59 | + domain=cookie.domain, |
| 60 | + path=cookie.path, |
| 61 | + expires=cookie.expires, |
| 62 | + secure=cookie.secure, |
| 63 | + httponly=cookie.httpOnly, |
| 64 | + samesite=cookie.sameSite, |
| 65 | + ) |
| 66 | + ) |
| 67 | + return morsel_obj |
| 68 | + |
| 69 | + async def __aenter__(self): |
| 70 | + """Async context manager support for engine -> ENTER""" |
| 71 | + await self.setup() |
| 72 | + return self |
| 73 | + |
| 74 | + async def __aexit__(self, exc_type, exc_val, exc_tb): |
| 75 | + """Async context manager support for engine -> EXIT""" |
| 76 | + await self.teardown() |
| 77 | + |
| 78 | + async def setup(self, **kwargs) -> None: |
| 79 | + """Set-up up the engine for crawling purpose.""" |
| 80 | + self.session = ClientSession( |
| 81 | + connector=self._connector, |
| 82 | + cookies=self.cookies, |
| 83 | + headers=self.headers, |
| 84 | + trust_env=True, |
| 85 | + **kwargs, |
| 86 | + ) |
| 87 | + |
| 88 | + async def teardown(self) -> None: |
| 89 | + """Cleans up the engine.""" |
| 90 | + await self.session.close() |
| 91 | + |
| 92 | + async def base(self, url: pydantic.AnyUrl, method: str, data: dict, **kwargs) -> str: |
| 93 | + """Base Method for protocol to retrieve a list of URL.""" |
| 94 | + |
| 95 | + async with self.session.request( |
| 96 | + method, url, data=data, headers=self.headers, **self.proxy, **kwargs |
| 97 | + ) as response: |
| 98 | + return await response.text() |
| 99 | + |
| 100 | + async def get(self, urls: list[pydantic.AnyUrl], **kwargs) -> list[str] | str: |
| 101 | + """GET HTTP Method for protocol to retrieve a list of URL.""" |
| 102 | + tasks = [self.base(url, "GET", None, **kwargs) for url in urls] |
| 103 | + return await asyncio.gather(*tasks) |
| 104 | + |
| 105 | + async def post( |
| 106 | + self, urls: list[pydantic.AnyUrl], datas: list[dict], **kwargs |
| 107 | + ) -> list[str] | str: |
| 108 | + """POST HTTP Method for protocol to crawl a list of URL.""" |
| 109 | + tasks = [self.base(url, "POST", data=data, **kwargs) for url, data in zip(urls, datas)] |
| 110 | + return await asyncio.gather(*tasks) |
| 111 | + |
| 112 | + async def put( |
| 113 | + self, urls: list[pydantic.AnyUrl], datas: list[dict], **kwargs |
| 114 | + ) -> list[str] | str: |
| 115 | + """PUT HTTP Method for protocol to crawl a list of URL.""" |
| 116 | + tasks = [self.base(url, "PUT", data=data) for url, data in zip(urls, datas)] |
| 117 | + return await asyncio.gather(*tasks) |
| 118 | + |
| 119 | + async def delete( |
| 120 | + self, urls: list[pydantic.AnyUrl], datas: list[dict], **kwargs |
| 121 | + ) -> list[str] | str: |
| 122 | + """DELETE HTTP Method for protocol to crawl a list of URL.""" |
| 123 | + tasks = [self.base(url, "DELETE", data=data, **kwargs) for url, data in zip(urls, datas)] |
| 124 | + return await asyncio.gather(*tasks) |
0 commit comments