Skip to content

Commit

Permalink
ADD:增加代理功能
Browse files Browse the repository at this point in the history
  • Loading branch information
ShilongLee committed Oct 2, 2024
1 parent 4dd60b9 commit f6f3425
Show file tree
Hide file tree
Showing 3 changed files with 112 additions and 100 deletions.
94 changes: 94 additions & 0 deletions data/driver.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,3 +87,97 @@ async def expire(self, id: str) -> bool:
logger.error(f'failed to save cookies, error: {e}')
await conn.rollback()
return False

class Proxies(SqliteStore):
def __init__(self, store_path):
super().__init__(store_path)
self.primary_key = 'id'
self.table_name = 'proxies'
self._create_table()

def _create_table(self):
with closing(self._get_sync_connection()) as conn, closing(conn.cursor()) as cursor:
try:
sql = f'''
CREATE TABLE IF NOT EXISTS {self.table_name} (
{self.primary_key} INTEGER PRIMARY KEY AUTOINCREMENT,
url VARCHAR(512) NOT NULL,
enable INTEGER NOT NULL,
ct INTEGER NOT NULL,
ut INTEGER NOT NULL
)
'''
cursor.execute(sql)
conn.commit()
except Exception as e:
logger.error(f'failed to create table, error: {e}')

async def save(self, url: str = '', enable: int = 1, id: int = 0) -> bool:
ct = ut = int(time.time())
async with self._get_connection() as conn:
try:
sql = f'UPDATE {self.table_name} SET url = ?, enable = ?, ut = ? WHERE id = ?'
await conn.execute(sql, (url, enable, ut, id))
if conn.total_changes == 0:
sql = f'INSERT INTO {self.table_name} (url, enable, ct, ut) VALUES (?, ?, ?, ?)'
await conn.execute(sql, (url, enable, ct, ut))
await conn.commit()
return True
except Exception as e:
logger.error(f'failed to save proxy, error: {e}')
await conn.rollback()
return False

async def remove(self, id: int) -> bool:
async with self._get_connection() as conn:
try:
sql = f'DELETE FROM {self.table_name} WHERE id = ?'
await conn.execute(sql, (str(id)))
await conn.commit()
return True
except Exception as e:
logger.error(f'failed to remove proxy, error: {e}')
await conn.rollback()
return False

async def load(self, offset: int = 0, limit: int = 0) -> list:
async with self._get_connection() as conn:
try:
if limit == 0:
sql = f'SELECT * FROM {self.table_name}'
cursor = await conn.execute(sql)
else:
sql = f'SELECT * FROM {self.table_name} LIMIT ? OFFSET ?'
cursor = await conn.execute(sql, (limit, offset))
results = await cursor.fetchall()
return [dict(row) for row in results]
except Exception as e:
logger.error(f'failed to load proxies, error: {e}')
await conn.rollback()
return []

async def enable(self, id: int) -> bool:
ut = int(time.time())
async with self._get_connection() as conn:
try:
sql = f'UPDATE {self.table_name} SET enable = ?, ut = ? WHERE id = ?'
await conn.execute(sql, (1, ut, id))
await conn.commit()
return True
except Exception as e:
logger.error(f'failed to save proxies, error: {e}')
await conn.rollback()
return False

async def disable(self, id: int) -> bool:
ut = int(time.time())
async with self._get_connection() as conn:
try:
sql = f'UPDATE {self.table_name} SET enable = ?, ut = ? WHERE id = ?'
await conn.execute(sql, (0, ut, id))
await conn.commit()
return True
except Exception as e:
logger.error(f'failed to save proxies, error: {e}')
await conn.rollback()
return False
19 changes: 17 additions & 2 deletions lib/requests/requests.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import httpx
import json
import time
from data.driver import Proxies

proxyModel = Proxies("data/proxies/proxies.db")
proxies = []

class Response:
def __init__(self, status_code, text):
Expand All @@ -21,14 +26,24 @@ async def wrapper(*args, **kwargs):

return wrapper

async def get_proxy():
global proxies
proxies = await proxyModel.load()
if(len(proxies) == 0):
return None
proxy = proxies[int(int(time.time()) / 300) % len(proxies)]
return proxy['url']

@retry_request
async def get(url, headers=None, params=None) -> Response:
async with httpx.AsyncClient() as client:
proxy = await get_proxy()
async with httpx.AsyncClient(proxy=proxy) as client:
response = await client.get(url, headers=headers, params=params)
return Response(response.status_code, response.text)

@retry_request
async def post(url, headers=None, data=None, json=None) -> Response:
async with httpx.AsyncClient() as client:
proxy = await get_proxy()
async with httpx.AsyncClient(proxy=proxy) as client:
response = await client.post(url, headers=headers, json=json, data=data)
return Response(response.status_code, response.text)
99 changes: 1 addition & 98 deletions service/proxies/models.py
Original file line number Diff line number Diff line change
@@ -1,100 +1,3 @@
from data.driver import SqliteStore
from contextlib import closing
from lib.logger import logger
import time

class Proxies(SqliteStore):
def __init__(self, store_path):
super().__init__(store_path)
self.primary_key = 'id'
self.table_name = 'proxies'
self._create_table()

def _create_table(self):
with closing(self._get_sync_connection()) as conn, closing(conn.cursor()) as cursor:
try:
sql = f'''
CREATE TABLE IF NOT EXISTS {self.table_name} (
{self.primary_key} INTEGER PRIMARY KEY AUTOINCREMENT,
url VARCHAR(512) NOT NULL,
enable INTEGER NOT NULL,
ct INTEGER NOT NULL,
ut INTEGER NOT NULL
)
'''
cursor.execute(sql)
conn.commit()
except Exception as e:
logger.error(f'failed to create table, error: {e}')

async def save(self, url: str = '', enable: int = 1, id: int = 0) -> bool:
ct = ut = int(time.time())
async with self._get_connection() as conn:
try:
sql = f'UPDATE {self.table_name} SET url = ?, enable = ?, ut = ? WHERE id = ?'
await conn.execute(sql, (url, enable, ut, id))
if conn.total_changes == 0:
sql = f'INSERT INTO {self.table_name} (url, enable, ct, ut) VALUES (?, ?, ?, ?)'
await conn.execute(sql, (url, enable, ct, ut))
await conn.commit()
return True
except Exception as e:
logger.error(f'failed to save proxy, error: {e}')
await conn.rollback()
return False

async def remove(self, id: int) -> bool:
async with self._get_connection() as conn:
try:
sql = f'DELETE FROM {self.table_name} WHERE id = ?'
await conn.execute(sql, (str(id)))
await conn.commit()
return True
except Exception as e:
logger.error(f'failed to remove proxy, error: {e}')
await conn.rollback()
return False

async def load(self, offset: int = 0, limit: int = 0) -> list:
async with self._get_connection() as conn:
try:
if limit == 0:
sql = f'SELECT * FROM {self.table_name}'
cursor = await conn.execute(sql)
else:
sql = f'SELECT * FROM {self.table_name} LIMIT ? OFFSET ?'
cursor = await conn.execute(sql, (limit, offset))
results = await cursor.fetchall()
return [dict(row) for row in results]
except Exception as e:
logger.error(f'failed to load proxies, error: {e}')
await conn.rollback()
return []

async def enable(self, id: int) -> bool:
ut = int(time.time())
async with self._get_connection() as conn:
try:
sql = f'UPDATE {self.table_name} SET enable = ?, ut = ? WHERE id = ?'
await conn.execute(sql, (1, ut, id))
await conn.commit()
return True
except Exception as e:
logger.error(f'failed to save proxies, error: {e}')
await conn.rollback()
return False

async def disable(self, id: int) -> bool:
ut = int(time.time())
async with self._get_connection() as conn:
try:
sql = f'UPDATE {self.table_name} SET enable = ?, ut = ? WHERE id = ?'
await conn.execute(sql, (0, ut, id))
await conn.commit()
return True
except Exception as e:
logger.error(f'failed to save proxies, error: {e}')
await conn.rollback()
return False
from data.driver import Proxies

proxies = Proxies("data/proxies/proxies.db")

0 comments on commit f6f3425

Please sign in to comment.