Rate this code
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
}
@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.
code
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.
code
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']))
]
# Mapeo de los encabezados a los nuevos nombres de campos
mapped_headers = [FIELD_MAP.get(header, header.lower().replace(' ', '_')) for header in headers]
data = []
for row in table.find_all('tr')[1:]:
cells = row.find_all('td')
if len(cells) != len(mapped_headers):
if not ignore_row_length_warning:
logger.warning(
"La fila no coincide con la longitud del encabezado. Omitiendo fila"
)
continue
row_data = {
mapped_header: cell.get_text(strip=True) or None
for mapped_header, cell in zip(mapped_headers, cells)
}
data.append(row_data)
return data
async def fetch_and_parse(
scraper: AsyncScraper,
pon: int,
onu_group: int
) -> List[Dict[str, Optional[str]]]:
"""
Obtiene y analiza información óptica para un PON y grupo ONU específico.
code
Args:
scraper (AsyncScraper): La instancia del scraper.
pon (int): Identificador PON.
onu_group (int): Identificador del grupo ONU.
Retorna:
List[Dict[str, Optional[str]]]: Lista de datos analizados.
"""
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 parsed_data
async def process_batch(
scraper: AsyncScraper,
batch: List[tuple]
) -> List[Dict[str, Optional[str]]]:
"""
Procesa un lote de combinaciones de PON y grupo ONU.
code
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
]
results = await asyncio.gather(*tasks, return_exceptions=True)
flat_results = []
for result in results:
if isinstance(result, Exception):
scraper.logger.error(
f"La tarea del lote falló con excepción: {result}"
)
continue
flat_results.extend(result)
return flat_results
async def collect_data(
scraper: AsyncScraper
) -> List[Dict[str, Optional[str]]]:
"""
Recopila datos obteniendo y analizando información para todas las combinaciones
de PON y grupo ONU.
code
Args:
scraper (AsyncScraper): La instancia del scraper.
Retorna:
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: 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)
aggregated_data.extend(results)
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 transferencia por partes.
code
Args:
request (web.Request): La petición HTTP entrante.
Retorna:
web.StreamResponse: La respuesta JSON transmitiendo los datos.
"""
start_time = datetime.now()
logger.info(
f"Petición recibida en {CONFIG['ENDPOINT']} a las {start_time}"
)
# Inicializar la respuesta
resp = web.StreamResponse(
status=200,
reason='OK',
headers={
'Content-Type': 'application/json',
'Transfer-Encoding': 'chunked',
}
)
await resp.prepare(request)
try:
scraper = ScraperFactory.create_scraper()
async with scraper:
if not await scraper.login(CONFIG['USERNAME'], CONFIG['PASSWORD']):
error_data = {
"error": "Error de inicio de sesión. Por favor, verifique las credenciales."
}
json_data = json.dumps(error_data, indent=2, ensure_ascii=False)
await resp.write(json_data.encode('utf-8'))
await resp.write_eof()
return resp
# Iniciar el JSON con el campo "data"
await resp.write(b'{\n "data": [\n')
first_record = True
# 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
for i in range(0, len(all_combinations), scraper.config['BATCH_SIZE']):
batch = all_combinations[i:i + scraper.config['BATCH_SIZE']]
logger.info(f"Procesando lote {i // scraper.config['BATCH_SIZE'] + 1}")
results = await process_batch(scraper, batch)
for record in results:
if not first_record:
# Añadir coma antes de cada nuevo registro después del primero
await resp.write(b',\n')
else:
first_record = False
# Convertir el registro a JSON con indentación y asegurar caracteres Unicode
record_json = json.dumps(record, indent=4, ensure_ascii=False)
# Añadir indentación al registro
indented_record = '\n'.join([' ' + line for line in record_json.split('\n')])
await resp.write(indented_record.encode('utf-8'))
# Asegurar que los datos se envían inmediatamente
await resp.drain()
# Finalizar el arreglo "data" y añadir "processing_time"
end_time = datetime.now()
duration = end_time - start_time
final_json = f'\n ],\n "processing_time": "{duration}"\n}}\n'
await resp.write(final_json.encode('utf-8'))
await resp.write_eof()
logger.info(f"Recopilación de datos completa. Duración: {duration}")
except ClientError as e:
logger.error(f"Error de cliente en handle_data: {e}")
error_event = {
"error": f"Error de cliente: {e}"
}
json_data = json.dumps(error_event, indent=2, ensure_ascii=False)
await resp.write(json_data.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 = {
"error": f"Error inesperado: {e}"
}
json_data = json.dumps(error_event, indent=2, ensure_ascii=False)
await resp.write(json_data.encode('utf-8'))
await resp.write_eof()
return resp
async def init_app() -> web.Application:
"""
Inicializa la aplicación web aiohttp.
code
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.
code
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()
code
# 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)
Overall, your Python script demonstrates a solid understanding of asynchronous programming with asyncio and aiohttp, effective use of logging, and structured code organization. Below is a comprehensive evaluation of your code, highlighting its strengths, areas for improvement, and specific suggestions to enhance its quality, security, and maintainability.
Overall Rating: 8/10
Strengths
Asynchronous Design:
Utilizes asyncio and aiohttp effectively to handle concurrent HTTP requests, enhancing performance and responsiveness.
Implements batching and semaphore controls (asyncio.Semaphore) to manage the number of concurrent requests, preventing server overload.
Structured Logging:
Employs a singleton logger with colorlog for colored and consistent logging output.
Comprehensive logging at various levels (INFO, WARNING, ERROR, CRITICAL) provides clear insights into the script’s operations and potential issues.
Modular Design:
Uses factory classes (ConfigFactory, ScraperFactory) to create configurations and scraper instances, promoting reusability and ease of maintenance.
Well-organized code with clear separation of concerns, making it easier to navigate and understand.
Error Handling:
Implements robust error handling with retries, delays, and detailed logging for network-related operations.
Gracefully handles unexpected exceptions, ensuring the server remains stable.
Documentation:
Comprehensive docstrings and comments throughout the codebase enhance readability and provide clear explanations of functionalities.
Efficient Resource Management:
Proper use of asynchronous context managers (__aenter__ and __aexit__) to manage the lifecycle of HTTP sessions ensures resources are handled correctly.
Configuration Flexibility:
Allows configuration through command-line arguments (argparse), enabling flexibility in script behavior without modifying the code.
Areas for Improvement
Security Concerns:
Hardcoded Credentials: Storing sensitive information like USERNAME and PASSWORD directly in the code is a significant security risk.
SSL Verification Disabled: The SSL context is set to not verify certificates (verify_mode = ssl.CERT_NONE), exposing the application to potential Man-in-the-Middle (MitM) attacks.
Configuration Management:
Lack of External Configuration: Relying solely on a hardcoded CONFIG dictionary limits flexibility. Externalizing configurations using environment variables or configuration files can enhance security and adaptability.
Error Handling Enhancements:
Specific Exception Handling: Catching broad exceptions (except Exception as e) can obscure specific issues. More granular exception handling can improve debugging and reliability.
Detailed Error Responses: When errors occur, providing more context or error codes in responses can aid in troubleshooting.
Code Redundancy:
Repeated Combinations Generation: Both collect_data and handle_data generate all combinations of PON and ONU groups. Consolidating this can reduce redundancy.
Duplicate Parsing Logic: The collect_data function is not used in the handle_data handler, leading to similar logic being implemented in multiple places.
Performance Optimization:
HTML Parsing Efficiency: While using BeautifulSoup with the lxml parser is efficient, further optimizations like caching parsed results or minimizing parsing operations can enhance performance.
Concurrency Limits: While a semaphore is used to limit concurrent requests, further fine-tuning based on actual server capabilities and network conditions might be beneficial.
Extensibility:
Limited CLI Arguments: Currently, only one CLI argument is supported. Considering additional arguments for configurations like BASE_URL, PORT, etc., can make the script more versatile.
Specific Suggestions
Enhance Security:
Externalize Credentials:
Environment Variables: Utilize environment variables to store sensitive information. Libraries like python-dotenv can help manage these variables.
python
import os
CONFIG = {
'BASE_URL': os.getenv('BASE_URL', 'https://10.0.0.2'),
'USERNAME': os.getenv('USERNAME', 'misael_campos'),
'PASSWORD': os.getenv('PASSWORD', 'd337O8AetR3p4'),
# ... other configurations
}
Configuration Files: Use configuration files (e.g., YAML, JSON) with proper access controls to manage settings.
Enable SSL Verification:
Remove or make configurable the SSL context settings to ensure secure connections.
python
self.ssl_context.verify_mode = ssl.CERT_REQUIRED
Provide an option to specify certificate paths if necessary.
Improve Configuration Management:
Use dotenv or Similar Libraries:
Incorporate libraries like python-dotenv to manage environment variables more effectively.
Expand CLI Arguments:
Allow users to specify configurations like BASE_URL, USERNAME, PASSWORD, PORT, etc., via command-line arguments.
python
parser.add_argument('--base-url', type=str, help='Base URL of the router')
parser.add_argument('--port', type=int, default=8080, help='Port number for the server')
# ... other arguments
Refine Error Handling:
Catch Specific Exceptions:
Handle specific exceptions like aiohttp.ClientResponseError, , etc., separately to provide more precise error information.
Conclusion
Your script is well-structured, leveraging asynchronous programming paradigms to achieve efficient and scalable operations. By addressing the highlighted security concerns, enhancing configuration management, refining error handling, and optimizing performance, you can significantly improve the robustness and maintainability of your application. Implementing these suggestions will not only enhance the script's functionality but also ensure it adheres to best practices in software development.
Consolidate the generation of PON and ONU group combinations into a single function to avoid repetition.
Utilize collect_data:
Implement collect_data within the handle_data handler to maintain consistency and reduce duplicated logic.
python
data = await collect_data(scraper)
# Stream data accordingly
Enhance Documentation:
Language Consistency:
While comments are in Spanish, consider aligning with standard conventions (typically English) for broader accessibility, especially if collaborating with an international team.
Expand Docstrings:
Provide more detailed explanations in docstrings, including parameter types and return values where applicable.
Implement Testing:
Unit Tests:
Write unit tests for critical components like the AsyncScraper, ensuring functionalities like login, data fetching, and parsing work as expected.
Integration Tests:
Test the entire flow, including the HTTP endpoint, to verify end-to-end functionality.
Enhance Performance:
Cache Repeated Data:
If certain data or HTML structures are frequently requested and remain unchanged, consider caching parsed results to reduce processing time.
Adjust Concurrency Dynamically:
Implement dynamic concurrency controls based on real-time server response times and load.
User Feedback and Monitoring:
Health Checks:
Implement additional endpoints or health checks to monitor the server’s status and performance.
Metrics Collection:
Utilize libraries like prometheus_client to collect and expose metrics for monitoring purposes.