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

60 lines
1.8 KiB
Python
Raw Normal View History

2023-01-02 00:09:55 +03:00
from __future__ import annotations
import asyncio
2023-02-19 21:44:15 +03:00
from dataclasses import dataclass
2023-01-02 00:09:55 +03:00
from time import perf_counter
2023-02-19 21:44:15 +03:00
from typing import Union
2023-01-02 00:09:55 +03:00
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
from .constants import HEADERS
2023-02-19 21:44:15 +03:00
from .null_context import AsyncNullContext
2023-01-15 13:05:16 +03:00
2023-02-19 21:44:15 +03:00
@dataclass(repr=False, unsafe_hash=True)
class Proxy:
2023-01-04 17:49:45 +03:00
__slots__ = ("geolocation", "host", "is_anonymous", "port", "timeout")
2023-02-19 21:44:15 +03:00
host: str
port: int
2023-01-15 13:05:16 +03:00
2023-01-02 00:09:55 +03:00
async def check(
2023-01-04 20:24:44 +03:00
self,
*,
2023-01-15 13:05:16 +03:00
website: str,
2023-02-19 21:44:15 +03:00
sem: Union[asyncio.Semaphore, AsyncNullContext],
2023-01-04 20:24:44 +03:00
cookie_jar: AbstractCookieJar,
2023-01-15 00:22:17 +03:00
proto: ProxyType,
2023-01-07 11:57:57 +03:00
timeout: ClientTimeout,
set_geolocation: bool,
2023-01-02 00:09:55 +03:00
) -> None:
async with sem:
start = perf_counter()
2023-06-27 12:04:44 +03:00
connector = ProxyConnector(
proxy_type=proto, host=self.host, port=self.port
)
2023-04-17 16:48:11 +03:00
async with ClientSession(
2023-01-15 13:05:16 +03:00
connector=connector,
cookie_jar=cookie_jar,
timeout=timeout,
2023-02-19 21:44:15 +03:00
headers=HEADERS,
2023-06-27 12:04:44 +03:00
) as session, session.get(
website, raise_for_status=True
) as response:
if set_geolocation:
2023-01-15 13:05:16 +03:00
await response.read()
2023-01-02 00:09:55 +03:00
self.timeout = perf_counter() - start
if set_geolocation:
2023-04-17 16:40:20 +03:00
data = await response.json(content_type=None)
2023-01-15 13:05:16 +03:00
self.is_anonymous = self.host != data["query"]
self.geolocation = (
f"|{data['country']}|{data['regionName']}|{data['city']}"
2023-01-15 13:05:16 +03:00
)
2023-01-02 00:09:55 +03:00
2023-02-19 21:44:15 +03:00
def as_str(self, *, include_geolocation: bool) -> str:
2023-01-04 17:49:45 +03:00
if include_geolocation:
return f"{self.host}:{self.port}{self.geolocation}"
return f"{self.host}:{self.port}"