nova-api/api/proxies.py

90 lines
2.5 KiB
Python
Raw Normal View History

2023-07-19 23:51:28 +02:00
"""This module makes it easy to implement proxies by providing a class.."""
2023-06-28 15:21:14 +02:00
import os
import socket
import asyncio
2023-07-25 02:42:53 +02:00
import aiohttp
import aiohttp_socks
2023-06-28 15:21:14 +02:00
from dotenv import load_dotenv
load_dotenv()
class Proxy:
"""Represents a proxy. The type can be either http, https, socks4 or socks5."""
def __init__(self,
proxy_type: str='http',
host: str='127.0.0.1',
port: int=8080,
username: str=None,
password: str=None
):
self.proxy_type = proxy_type
2023-07-25 19:45:21 +02:00
self.ip_address = host
self.host = socket.gethostbyname(host)
2023-06-28 15:21:14 +02:00
self.port = port
self.username = username
self.password = password
2023-07-25 19:45:21 +02:00
self.url = f'socks5://{self.username}:{self.password}@{self.ip_address}:{self.port}'
2023-07-25 02:42:53 +02:00
async def initialize_connector(self, connector):
async with aiohttp.ClientSession(
connector=connector,
timeout=aiohttp.ClientTimeout(total=10),
raise_for_status=True
) as session:
async with session.request(
method='get',
url='https://checkip.amazonaws.com',
headers={'Content-Type': 'application/json'}
) as response:
detected_ip = await response.text()
print(f'Detected IP: {detected_ip}')
return detected_ip.strip()
async def get_connector(self):
proxy_types = {
'http': aiohttp_socks.ProxyType.HTTP,
'https': aiohttp_socks.ProxyType.HTTP,
'socks4': aiohttp_socks.ProxyType.SOCKS4,
'socks5': aiohttp_socks.ProxyType.SOCKS5
}
connector = aiohttp_socks.ProxyConnector(
proxy_type=proxy_types[self.proxy_type],
host=self.ip_address,
port=self.port,
rdns=False,
username=self.username,
password=self.password
)
await self.initialize_connector(connector)
return connector
default_proxy = Proxy(
2023-06-28 15:21:14 +02:00
proxy_type=os.getenv('PROXY_TYPE', 'http'),
host=os.getenv('PROXY_HOST', '127.0.0.1'),
2023-07-25 02:42:53 +02:00
port=int(os.getenv('PROXY_PORT', '8080')),
2023-06-28 15:21:14 +02:00
username=os.getenv('PROXY_USER'),
password=os.getenv('PROXY_PASS')
)
2023-07-25 19:45:21 +02:00
if __name__ == '__main__':
import requests
print(default_proxy.url)
received_ip = requests.get(
'https://checkip.amazonaws.com',
timeout=5,
proxies={
'https': default_proxy.url
}
2023-07-25 19:45:21 +02:00
).text.strip()
print(received_ip)