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.
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']))
]
# 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.
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.
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.
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.
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.
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)
Certainly! Here's a comprehensive review of your Python script, assessing various aspects such as functionality, code quality, best practices, security, and maintainability.
Overall Rating: 8/10
Strengths
Asynchronous Design:
Usage of asyncio and aiohttp: Leveraging asynchronous programming for both the client (scraper) and server (aiohttp web server) ensures high performance and responsiveness, especially when dealing with I/O-bound tasks.
Concurrency Control: Utilization of asyncio.Semaphore to limit the number of concurrent requests prevents server overload and manages resources efficiently.
Modular Structure:
Classes and Factories: The use of classes like AsyncScraper, ConfigFactory, and ScraperFactory encapsulates functionality, promoting reusability and separation of concerns.
Function Decomposition: Functions like fetch_and_parse, process_batch, and collect_data break down complex workflows into manageable steps, enhancing readability and maintainability.
Robust Logging:
Singleton Logger: Implementing a singleton pattern for the logger ensures consistent logging across the application.
Color-Coded Logs: Using colorlog improves log readability, making it easier to distinguish between different log levels.
Comprehensive Logging Messages: Informative logs at various stages facilitate easier debugging and monitoring.
Error Handling and Retries:
Retry Mechanism: Implementing retries with delays for network operations increases the resilience of the scraper against transient issues.
Exception Handling: Catching specific exceptions like aiohttp.ClientResponseError and general exceptions ensures that unexpected errors are gracefully managed.
Configuration Management:
Centralized CONFIG Dictionary: Storing configuration parameters in a centralized dictionary makes it easier to manage and update settings.
Docstrings: Comprehensive docstrings for classes and functions provide clarity on their purpose, inputs, and outputs, aiding future maintenance and collaboration.
In-Code Comments: Helpful comments explain non-trivial sections of the code.
Efficient Data Processing:
Batch Processing: Handling data in batches optimizes resource usage and can improve throughput.
HTML Parsing with BeautifulSoup: Utilizing BeautifulSoup with the lxml parser ensures efficient and reliable HTML parsing.
Areas for Improvement
Security Concerns:
Hard-Coded Credentials: Storing sensitive information like USERNAME and PASSWORD directly in the code is a significant security risk. Recommendation:
Environment Variables: Use environment variables or configuration files (e.g., .env with python-dotenv) to manage sensitive data.
Secrets Management: For production environments, consider using dedicated secrets management services or tools.
Configuration Management Enhancements:
Immutable Configuration: Currently, the CONFIG dictionary is mutable and globally accessible. Recommendation:
Use Immutable Structures: Consider using dataclasses or pydantic models to define configuration structures, which can provide validation and immutability.
Separate Configuration Sources: Allow configurations to be loaded from multiple sources (e.g., environment variables, files, command-line arguments) in a prioritized manner.
Logging Enhancements:
Sensitive Information Exposure: Ensure that logs do not inadvertently capture or expose sensitive information such as credentials or personal data.
Log Rotation and Management: For long-running applications, implement log rotation to prevent log files from growing indefinitely.
Error Handling Refinement:
Granular Exception Handling: While broad exception handling ensures that the application doesn't crash unexpectedly, more granular handling can provide better insights and control over different error scenarios.
Custom Exceptions: Define and use custom exception classes to represent specific error states, improving clarity and error management.
Resource Management:
Session Management: Currently, a new AsyncScraper instance is created for each HTTP request. Recommendation:
Connection Pooling: Implement a connection pool or reuse scraper instances to optimize resource usage and reduce overhead.
Detailed Feedback by Sections
Imports:
Well-organized imports separated into standard library and third-party modules.
Consider removing unused imports (if any) to keep the namespace clean.
Configuration (CONFIG):
As mentioned, avoid hard-coding sensitive data.
Use more descriptive variable names where possible.
Logging (LoggerSingleton):
Effective use of a singleton pattern to ensure a single logger instance.
Excellent use of color-coded logs for better visibility.
Factories (ConfigFactory and ScraperFactory):
Good abstraction for creating configurations and scraper instances.
Consider expanding factories if more complex instantiation logic is needed in the future.
get_all_ip_addresses:
Efficiently retrieves non-local IPv4 addresses.
Utilizing lru_cache is a clever way to cache results and avoid redundant computations.
AsyncScraper Class:
Comprehensive methods for login and fetching data with proper retries and error handling.
SSL context is configured to ignore certificate verification, which might be necessary for internal networks but poses security risks. Recommendation:
Secure SSL Practices: Re-enable certificate verification in production environments if possible or handle certificates appropriately.
HTML Parsing (parse_html_table):
Efficient parsing using BeautifulSoup with the lxml parser.
Handles dynamic table structures by mapping headers and managing inconsistent row lengths.
Data Processing Functions:
fetch_and_parse, process_batch, collect_data: These functions work together seamlessly to fetch, parse, and aggregate data efficiently.
Error Handling: Errors during data fetching are logged, and processing continues without halting the entire operation.
Final Recommendations
Security First: Prioritize securing sensitive data and ensuring that the application does not expose vulnerabilities, especially when handling network operations and credentials.
Enhance Configurability: Make the application more flexible by allowing configurations to be loaded from various sources and making them immutable or validated.
Improve Testing and Documentation: Invest time in writing tests and enhancing documentation to facilitate easier maintenance and onboarding of new contributors.
Optimize Performance and Resource Management: Continuously monitor and optimize the application's performance, ensuring efficient use of resources and maintaining high availability.
By addressing the areas for improvement while maintaining the existing strengths, your script can become more robust, secure, and maintainable, making it even more effective for its intended purposes.
Graceful Shutdown: Ensure that all sessions and connections are properly closed during shutdown to prevent resource leaks.
Dependency Management:
Explicit Dependencies: Ensure that all external dependencies (aiohttp, colorlog, netifaces, BeautifulSoup, etc.) are listed explicitly in a requirements.txt or pyproject.toml file for easy installation and environment setup.
Version Pinning: Pin dependency versions to ensure consistent behavior across different environments.
Code Readability and PEP 8 Compliance:
Naming Conventions: While generally good, ensure consistency in naming (e.g., method names and variable names) following PEP 8 guidelines.
Line Length: Adhere to the recommended maximum line length (typically 79 or 99 characters) to improve readability.
Testing:
Unit Tests: Implement unit tests for critical components like the scraper, parsers, and configurations to ensure reliability and facilitate future changes.
Integration Tests: Test the application end-to-end to verify that all components interact as expected.
Performance Optimization:
Caching HTML Responses: If certain requests yield the same results over time, consider caching responses to reduce load and improve response times.
Efficient Parsing: Ensure that the HTML parsing logic is optimized, especially if dealing with large or complex HTML documents.
Internationalization and Localization:
Language Consistency: While docstrings and comments are in both English and Spanish, consider standardizing on one language to maintain consistency, especially if collaborating with a diverse team.
Aiohttp Server (handle_data, init_app, main):
Endpoint Handling: The server responds to HTTP GET requests, initiates data collection, and streams JSON responses incrementally.
Graceful Shutdown: Implements signal handlers for SIGINT and SIGTERM to allow graceful shutdowns, ensuring resources are cleaned up properly.
Incremental JSON Streaming: Useful for large datasets, enabling clients to start processing data before the entire payload is ready.
Command-Line Interface (parse_args):
Provides flexibility to modify behavior via command-line arguments.
Can be expanded to include more configurable parameters as needed.