Rate this code from 1 to 10, dont suggest more features, it's good as it is
import argparse
import asyncio
import json
import logging
import signal
import ssl
import sys
from datetime import datetime
from functools import lru_cache
from typing import Dict, List, Optional
import aiohttp
from aiohttp import web
from aiohttp.client_exceptions import ClientError
import colorlog
import netifaces
from bs4 import BeautifulSoup
Configuración del script
CONFIG = {
'BASE_URL': 'https://10.0.0.2',
'USERNAME': 'misael_campos',
'PASSWORD': 'd337O8AetR3p4',
'POST_ENDPOINT': '/action/pononuopticalinfo.html',
'WHO': 100,
'ONUID': 0,
'PON_RANGE': range(1, 17),
'ONU_GROUP_RANGE': range(0, 2),
'REQUEST_TIMEOUT': aiohttp.ClientTimeout(
total=240, # Tiempo de espera total de la operación
connect=120, # Tiempo de espera de conexión
sock_read=120 # Tiempo de espera de lectura del socket
),
'MAX_CONCURRENT_REQUESTS': 8, # Reducido para prevenir sobrecarga del servidor
'MAX_RETRIES': 3, # Número máximo de intentos de reintento
'RETRY_DELAY': 1, # Retraso entre reintentos en segundos
'BATCH_SIZE': 8, # Número de solicitudes concurrentes por lote
'HOST': '0.0.0.0', # Dirección del host
'PORT': 8080, # Número de puerto
'ENDPOINT': '/data', # Ruta del endpoint añadida
'IGNORE_ROW_LENGTH_WARNING': False # Nueva opción de configuración
}
Singleton Logger
class LoggerSingleton:
"""Singleton para garantizar una única instancia del logger."""
Asynchronous Design: Utilizes asyncio and effectively for handling asynchronous HTTP requests, which is excellent for performance and scalability.
@lru_cache(maxsize=None)
def get_all_ip_addresses(logger: logging.Logger) -> List[str]:
"""
Obtiene todas las direcciones IPv4 no locales de las interfaces de red de la máquina.
Retorna:
List[str]: Una lista de direcciones IPv4.
"""
try:
interfaces = netifaces.interfaces()
ips = [
addr.get('addr')
for iface in interfaces
for addr in netifaces.ifaddresses(iface).get(netifaces.AF_INET, [])
if addr.get('addr') and addr.get('addr') != '127.0.0.1'
]
return ips
except ValueError as ve:
logger.error(f"Error al obtener direcciones IP: {ve}")
except Exception as e:
logger.error(f"Error inesperado al obtener direcciones IP: {e}")
return []
class AsyncScraper:
"""
Scraper asíncrono para obtener información óptica de un router.
Atributos:
base_url (str): La URL base del router.
ssl_context (ssl.SSLContext): Contexto SSL para peticiones HTTPS.
session (aiohttp.ClientSession): La sesión HTTP para realizar peticiones.
sem (asyncio.Semaphore): Semáforo para limitar peticiones concurrentes.
"""
def __init__(self, base_url: str, config: Dict, logger: logging.Logger):
"""
Inicializa el AsyncScraper con la URL base proporcionada.
Args:
base_url (str): La URL base del router.
config (Dict): Diccionario de configuración.
logger (logging.Logger): Instancia del logger.
"""
self.base_url = base_url.rstrip('/')
self.config = config
self.logger = logger
self.ssl_context = ssl.create_default_context()
self.ssl_context.check_hostname = False
self.ssl_context.verify_mode = ssl.CERT_NONE
self.session: Optional[aiohttp.ClientSession] = None
self.sem = asyncio.Semaphore(self.config['MAX_CONCURRENT_REQUESTS'])
async def __aenter__(self):
"""
Entra en el gestor de contexto asíncrono, inicializando la sesión HTTP.
Retorna:
AsyncScraper: La instancia misma con una sesión activa.
"""
timeout = self.config['REQUEST_TIMEOUT']
self.session = aiohttp.ClientSession(
connector=aiohttp.TCPConnector(
ssl=self.ssl_context,
limit=self.config['MAX_CONCURRENT_REQUESTS']
),
timeout=timeout,
headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'}
)
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
"""
Sale del gestor de contexto asíncrono, cerrando la sesión HTTP.
Args:
exc_type: Tipo de excepción.
exc_val: Valor de la excepción.
exc_tb: Traza de la excepción.
"""
if self.session:
await self.session.close()
async def login(self, username: str, password: str) -> bool:
"""
Realiza el inicio de sesión en el router.
Args:
username (str): El nombre de usuario para la autenticación.
password (str): La contraseña para la autenticación.
Retorna:
bool: True si el inicio de sesión es exitoso, False en caso contrario.
"""
login_url = f"{self.base_url}/action/main.html"
login_data = {
'user': username,
'pass': password,
'button': 'Login',
'who': str(self.config['WHO']),
}
for attempt in range(self.config['MAX_RETRIES']):
try:
async with self.session.post(login_url, data=login_data) as response:
response.raise_for_status()
text = await response.text()
if "Sorry, you do not have access" in text:
self.logger.error("Error de inicio de sesión: Acceso denegado")
return False
elif "Error" in text or "Incorrect password" in text:
self.logger.error("Error de inicio de sesión: Credenciales incorrectas")
return False
self.logger.info("¡Inicio de sesión exitoso!")
return True
except aiohttp.ClientResponseError as e:
self.logger.error(
f"Error HTTP durante el intento de inicio de sesión {attempt + 1}: {e}"
)
except aiohttp.ClientConnectorError as e:
self.logger.error(
f"Error de conexión durante el intento de inicio de sesión {attempt + 1}: {e}"
)
except asyncio.TimeoutError:
self.logger.error(
f"Tiempo de espera agotado durante el intento de inicio de sesión {attempt + 1}"
)
except Exception as e:
self.logger.error(
f"Error inesperado durante el intento de inicio de sesión {attempt + 1}: {e}"
)
if attempt < self.config['MAX_RETRIES'] - 1:
await asyncio.sleep(self.config['RETRY_DELAY'])
self.logger.info(f"Reintentando inicio de sesión (Intento {attempt + 2})...")
else:
self.logger.error("Todos los intentos de inicio de sesión fallaron.")
return False
async def fetch_pon_onu_optical_info(self, pon: int, onu_group: int) -> Optional[str]:
"""
Obtiene información óptica PON ONU del router.
Args:
pon (int): Identificador PON.
onu_group (int): Identificador del grupo ONU.
Retorna:
Optional[str]: El contenido HTML si es exitoso, None en caso contrario.
"""
async with self.sem:
post_url = f"{self.base_url}{self.config['POST_ENDPOINT']}"
payload = {
'pon': pon,
'onu_group': onu_group,
'who': str(self.config['WHO']),
'onuid': str(self.config['ONUID'])
}
for attempt in range(self.config['MAX_RETRIES']):
try:
async with self.session.post(post_url, data=payload) as response:
response.raise_for_status()
content = await response.text()
self.logger.info(
f"Datos obtenidos exitosamente para PON {pon}, Grupo ONU {onu_group} "
f"(Intento {attempt + 1})"
)
return content
except aiohttp.ClientResponseError as e:
self.logger.warning(
f"Error HTTP {e.status} para PON {pon}, Grupo ONU {onu_group} "
f"(Intento {attempt + 1}): {e.message}"
)
except aiohttp.ClientConnectorError as e:
self.logger.warning(
f"Error de conexión para PON {pon}, Grupo ONU {onu_group} "
f"(Intento {attempt + 1}): {e}"
)
except asyncio.TimeoutError:
self.logger.warning(
f"Tiempo de espera agotado al obtener PON {pon}, Grupo ONU {onu_group} "
f"(Intento {attempt + 1})"
)
except Exception as e:
self.logger.warning(
f"Error inesperado al obtener PON {pon}, Grupo ONU {onu_group} "
f"(Intento {attempt + 1}): {e}"
)
if attempt < self.config['MAX_RETRIES'] - 1:
await asyncio.sleep(self.config['RETRY_DELAY'])
self.logger.info(f"Reintentando PON {pon}, Grupo ONU {onu_group}...")
else:
self.logger.error(
f"Todos los intentos fallaron para PON {pon}, Grupo ONU {onu_group}"
)
return None
@staticmethod
def parse_html_table(html_content: str, logger: logging.Logger,
ignore_row_length_warning: bool) -> List[Dict[str, Optional[str]]]:
"""
Analiza una tabla HTML y extrae datos en una lista de diccionarios.
Args:
html_content (str): El contenido HTML que contiene la tabla.
logger (logging.Logger): Instancia del logger.
ignore_row_length_warning (bool): Parámetro para ignorar advertencias de longitud de fila.
Retorna:
List[Dict[str, Optional[str]]]: Datos de la tabla analizados.
"""
if not html_content:
return []
soup = BeautifulSoup(html_content, 'lxml') # Usar parser más rápido
table = soup.find('table', border="1", cellpadding="4", cellspacing="0")
if not table:
logger.warning("No se encontró tabla en el contenido HTML")
return []
headers = [
th.get_text(strip=True) or f"Columna_{i + 1}"
for i, th in enumerate(table.find('tr').find_all(['td', 'th']))
]
data = []
for row in table.find_all('tr')[1:]:
cells = row.find_all('td')
if len(cells) != len(headers):
if not ignore_row_length_warning:
logger.warning(
"La fila no coincide con la longitud del encabezado. Omitiendo fila"
)
continue
row_data = {
header: cell.get_text(strip=True) or None
for header, cell in zip(headers, cells)
}
data.append(row_data)
return data
async def fetch_and_parse(
scraper: AsyncScraper,
pon: int,
onu_group: int
) -> Dict[int, Dict[int, List[Dict[str, Optional[str]]]]]:
"""
Obtiene y analiza información óptica para un PON y grupo ONU específico.
Args:
scraper (AsyncScraper): La instancia del scraper.
pon (int): Identificador PON.
onu_group (int): Identificador del grupo ONU.
Retorna:
Dict[int, Dict[int, List[Dict[str, Optional[str]]]]]: Datos analizados estructurados
por PON y grupo ONU.
"""
html_content = await scraper.fetch_pon_onu_optical_info(pon, onu_group)
parsed_data = AsyncScraper.parse_html_table(
html_content,
scraper.logger,
scraper.config['IGNORE_ROW_LENGTH_WARNING']
) if html_content else []
if not parsed_data:
scraper.logger.warning(
f"No se analizaron datos para PON {pon}, Grupo ONU {onu_group}"
)
return {pon: {onu_group: parsed_data}}
async def process_batch(
scraper: AsyncScraper,
batch: List[tuple]
) -> List[Dict]:
"""
Procesa un lote de combinaciones de PON y grupo ONU.
Args:
scraper (AsyncScraper): La instancia del scraper.
batch (List[tuple]): Una lista de tuplas (pon, onu_group).
Retorna:
List[Dict]: Una lista de diccionarios de datos analizados.
"""
tasks = [
fetch_and_parse(scraper, pon, onu_group)
for pon, onu_group in batch
]
return await asyncio.gather(*tasks, return_exceptions=True)
async def collect_data(
scraper: AsyncScraper
) -> Dict[int, Dict[int, List[Dict[str, Optional[str]]]]]:
"""
Recopila datos obteniendo y analizando información para todas las combinaciones
de PON y grupo ONU.
Args:
scraper (AsyncScraper): La instancia del scraper.
Retorna:
Dict[int, Dict[int, List[Dict[str, Optional[str]]]]]: Datos analizados agregados.
"""
# Crear todas las combinaciones de PON y grupos ONU usando comprehensions
all_combinations = [
(pon, onu_group)
for pon in scraper.config['PON_RANGE']
for onu_group in scraper.config['ONU_GROUP_RANGE']
]
# Procesar en lotes
aggregated_data: Dict[int, Dict[int, List[Dict[str, Optional[str]]]]] = {}
for i in range(0, len(all_combinations), scraper.config['BATCH_SIZE']):
batch = all_combinations[i:i + scraper.config['BATCH_SIZE']]
scraper.logger.info(f"Procesando lote {i // scraper.config['BATCH_SIZE'] + 1}")
results = await process_batch(scraper, batch)
for result in results:
if isinstance(result, Exception):
scraper.logger.error(
f"La tarea del lote falló con excepción: {result}"
)
continue
for pon, onu_data in result.items():
if pon not in aggregated_data:
aggregated_data[pon] = {}
aggregated_data[pon].update(onu_data)
return aggregated_data
async def handle_data(request: web.Request) -> web.StreamResponse:
"""
Manejador HTTP para el endpoint configurado.
Activa la recopilación de datos y transmite los datos JSON agregados de forma
incremental usando SSE.
Args:
request (web.Request): La petición HTTP entrante.
Retorna:
web.StreamResponse: La respuesta SSE transmitiendo los datos.
"""
start_time = datetime.now()
logger.info(
f"Petición recibida en {CONFIG['ENDPOINT']} a las {start_time}"
)
# Inicializar la respuesta SSE
resp = web.StreamResponse(
status=200,
reason='OK',
headers={
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
}
)
await resp.prepare(request)
try:
scraper = ScraperFactory.create_scraper()
async with scraper:
if not await scraper.login(CONFIG['USERNAME'], CONFIG['PASSWORD']):
error_data = json.dumps({
"error": "Error de inicio de sesión. Por favor, verifique las credenciales."
})
await resp.write(
f"event: error\ndata: {error_data}\n\n".encode('utf-8')
)
await resp.write_eof()
return resp
aggregated_data = await collect_data(scraper)
end_time = datetime.now()
duration = end_time - start_time
logger.info(f"Recopilación de datos completa. Duración: {duration}")
# Enviar los datos agregados como un evento SSE
json_data = json.dumps(aggregated_data)
sse_event = f"event: complete\ndata: {json_data}\n\n"
await resp.write(sse_event.encode('utf-8'))
await resp.write_eof()
except ClientError as e:
logger.error(f"Error de cliente en handle_data: {e}")
error_event = (
f"event: error\ndata: {{\"error\": \"Error de cliente: {e}\"}}\n\n"
)
await resp.write(error_event.encode('utf-8'))
await resp.write_eof()
except asyncio.CancelledError:
logger.warning("La petición fue cancelada.")
await resp.write_eof()
except Exception as e:
logger.error(f"Error inesperado en handle_data: {e}")
error_event = (
f"event: error\ndata: {{\"error\": \"Error inesperado: {e}\"}}\n\n"
)
await resp.write(error_event.encode('utf-8'))
await resp.write_eof()
return resp
async def init_app() -> web.Application:
"""
Inicializa la aplicación web aiohttp.
Retorna:
web.Application: La aplicación web aiohttp configurada.
"""
app = web.Application()
app.router.add_get(CONFIG['ENDPOINT'], handle_data) # Usar endpoint configurable
return app
def parse_args() -> argparse.Namespace:
"""
Analiza los argumentos de línea de comandos.
Retorna:
argparse.Namespace: Los argumentos de línea de comandos analizados.
"""
parser = argparse.ArgumentParser(description="Servidor Scraper Asíncrono")
parser.add_argument(
'--ignore-row-length-warnings',
action='store_true',
help='Ignorar advertencias sobre desajustes en la longitud de filas en tablas HTML.'
)
# Puedes agregar más parámetros CLI aquí si es necesario.
return parser.parse_args()
async def main():
"""
Punto de entrada principal para ejecutar el servidor web con apagado controlado.
"""
# Analizar argumentos CLI
args = parse_args()
# Actualizar CONFIG basado en argumentos CLI
CONFIG['IGNORE_ROW_LENGTH_WARNING'] = args.ignore_row_length_warnings
# Obtener todas las direcciones IP
local_ips = get_all_ip_addresses(logger)
if not local_ips:
logger.warning(
"No se encontraron direcciones IPv4 no locales. Usando 127.0.0.1 como respaldo"
)
local_ips = [CONFIG['HOST']]
endpoint = CONFIG.get('ENDPOINT', '/data')
logger.info(f"Iniciando servidor en el puerto {CONFIG['PORT']}")
logger.info("Accesible en las siguientes URLs:")
for ip in local_ips:
logger.info(f"http://{ip}:{CONFIG['PORT']}{endpoint}")
app = await init_app()
runner = web.AppRunner(app)
await runner.setup()
site = web.TCPSite(runner, host=CONFIG['HOST'], port=CONFIG['PORT'])
await site.start()
logger.info("El servidor está ahora en funcionamiento")
# Crear un evento para esperar el apagado
shutdown_event = asyncio.Event()
# Definir manejador de señales
def shutdown_signal_handler():
logger.info("Señal de apagado recibida")
shutdown_event.set()
loop = asyncio.get_running_loop()
for sig in (signal.SIGINT, signal.SIGTERM):
try:
loop.add_signal_handler(sig, shutdown_signal_handler)
except NotImplementedError:
# Los manejadores de señales no están implementados en algunas plataformas (ej., Windows)
logger.warning(f"Manejadores de señales no implementados para {sig}")
# Esperar hasta que se reciba una señal de apagado
await shutdown_event.wait()
logger.info("Apagando servidor...")
# Realizar pasos de apagado
await runner.shutdown()
await runner.cleanup()
logger.info("Servidor apagado exitosamente.")
if name == "main":
try:
asyncio.run(main())
except Exception as e:
logger.critical(f"Excepción no manejada: {e}")
sys.exit(1)
aiohttp
Structured Logging: Implements a singleton logger with colorlog for clear and colored log outputs, enhancing readability and debugging.
Configuration Management: Uses a centralized CONFIG dictionary with a factory pattern (ConfigFactory), allowing easy updates and management of configurations.
Robust Error Handling: Comprehensive error handling for HTTP requests, connection issues, and parsing errors ensures the application can handle unexpected scenarios gracefully.
Documentation: Well-documented with clear docstrings for classes and functions, making the codebase easier to understand and maintain.
Concurrency Control: Implements semaphores and batching to manage concurrent requests, preventing server overload.
Modular Design: Separation of concerns through factories and distinct classes (AsyncScraper, LoggerSingleton) enhances modularity and reusability.
Type Hinting: Utilizes type hints throughout the code, improving code clarity and aiding in static analysis.
Areas for Improvement:
Security: Storing sensitive information like USERNAME and PASSWORD directly in the code is risky. It's advisable to use environment variables or secure storage solutions to handle credentials.
Configuration Flexibility: While the factory pattern is used, integrating more dynamic configuration sources (e.g., external config files or environment variables) could enhance flexibility.
Logging Duplication Check: The logger setup includes a loop to remove duplicate handlers, which might not be necessary if handlers are managed more carefully during initialization.
Dependency Management: Ensure that all dependencies (like beautifulsoup4, colorlog, netifaces, etc.) are documented, possibly using a requirements.txt file for easier setup.
Overall, the code is well-structured, maintainable, and effectively addresses the problem it's designed to solve. Addressing the highlighted areas can further enhance its robustness and security.