Files
proxy-scraper-checker/proxy_scraper_checker/proxy.py
T

58 lines
1.9 KiB
Python
Raw Normal View History

2023-01-02 00:09:55 +03:00
from __future__ import annotations
import asyncio
from time import perf_counter
2023-01-07 11:57:57 +03:00
from aiohttp import ClientSession, ClientTimeout
2023-01-04 20:24:44 +03:00
from aiohttp.abc import AbstractCookieJar
2023-01-04 17:49:45 +03:00
from aiohttp_socks import ProxyConnector, ProxyType
2023-01-02 00:09:55 +03:00
class Proxy:
2023-01-04 17:49:45 +03:00
__slots__ = ("geolocation", "host", "is_anonymous", "port", "timeout")
def __init__(self, *, host: str, port: int) -> None:
self.host = host
self.port = port
2023-01-02 00:09:55 +03:00
async def check(
2023-01-04 20:24:44 +03:00
self,
*,
sem: asyncio.Semaphore,
cookie_jar: AbstractCookieJar,
2023-01-15 00:22:17 +03:00
proto: ProxyType,
2023-01-07 11:57:57 +03:00
timeout: ClientTimeout,
2023-01-02 00:09:55 +03:00
) -> None:
async with sem:
start = perf_counter()
2023-01-04 17:49:45 +03:00
async with self.get_connector(proto) as connector:
2023-01-04 20:24:44 +03:00
async with ClientSession(
2023-01-07 11:57:57 +03:00
connector=connector, cookie_jar=cookie_jar, timeout=timeout
2023-01-04 20:24:44 +03:00
) as session:
2023-01-02 00:09:55 +03:00
async with session.get(
"http://ip-api.com/json/?fields=8217",
raise_for_status=True,
) as response:
data = await response.json()
self.timeout = perf_counter() - start
2023-01-04 17:49:45 +03:00
self.is_anonymous = self.host != data["query"]
2023-01-02 00:09:55 +03:00
self.geolocation = "|{}|{}|{}".format(
data["country"], data["regionName"], data["city"]
)
2023-01-15 00:22:17 +03:00
def get_connector(self, proto: ProxyType) -> ProxyConnector:
return ProxyConnector(proxy_type=proto, host=self.host, port=self.port)
2023-01-04 17:49:45 +03:00
def as_str(self, include_geolocation: bool) -> str:
if include_geolocation:
return f"{self.host}:{self.port}{self.geolocation}"
return f"{self.host}:{self.port}"
2023-01-02 00:09:55 +03:00
def __eq__(self, other: object) -> bool:
if not isinstance(other, Proxy):
return NotImplemented
2023-01-04 17:49:45 +03:00
return self.host == other.host and self.port == other.port
2023-01-02 00:09:55 +03:00
def __hash__(self) -> int:
2023-01-04 17:49:45 +03:00
return hash((self.host, self.port))