solcuionado un problema con el restaurador de feeds

This commit is contained in:
jlimolina 2025-06-08 21:17:33 +00:00
parent 19ee3df515
commit 841f0e610b

120
app.py
View file

@ -41,14 +41,13 @@ def get_conn():
"""Devuelve una conexión nueva usando psycopg2 y el diccionario DB_CONFIG.""" """Devuelve una conexión nueva usando psycopg2 y el diccionario DB_CONFIG."""
return psycopg2.connect(**DB_CONFIG) return psycopg2.connect(**DB_CONFIG)
MAX_FALLOS = 5 # Número máximo de fallos antes de desactivar el feed MAX_FALLOS = 5
# ====================================== # ======================================
# Filtro de Plantilla para HTML Seguro # Filtro de Plantilla para HTML Seguro
# ====================================== # ======================================
@app.template_filter('safe_html') @app.template_filter('safe_html')
def safe_html(text): def safe_html(text):
"""Sanitiza el HTML para prevenir ataques XSS, permitiendo etiquetas seguras."""
if not text: if not text:
return "" return ""
allowed_tags = {'a', 'abbr', 'b', 'strong', 'i', 'em', 'p', 'br', 'img'} allowed_tags = {'a', 'abbr', 'b', 'strong', 'i', 'em', 'p', 'br', 'img'}
@ -114,9 +113,6 @@ def home():
return render_template("noticias.html", noticias=noticias, categorias=categorias, continentes=continentes, paises=paises, return render_template("noticias.html", noticias=noticias, categorias=categorias, continentes=continentes, paises=paises,
cat_id=int(cat_id) if cat_id else None, cont_id=int(cont_id) if cont_id else None, pais_id=int(pais_id) if pais_id else None) cat_id=int(cat_id) if cat_id else None, cont_id=int(cont_id) if cont_id else None, pais_id=int(pais_id) if pais_id else None)
# Aquí incluyo el resto de rutas que habías creado, con la gestión de conexión mejorada
# (El código es largo, si quieres omitir alguna parte que no uses, puedes hacerlo)
@app.route("/feeds") @app.route("/feeds")
def feeds(): def feeds():
feeds_, categorias, continentes, paises = [], [], [], [] feeds_, categorias, continentes, paises = [], [], [], []
@ -212,6 +208,100 @@ def reactivar_feed(feed_id):
flash(f"Error al reactivar el feed: {db_err}", "error") flash(f"Error al reactivar el feed: {db_err}", "error")
return redirect(url_for("feeds")) return redirect(url_for("feeds"))
# ===================================================================
# [INICIO DEL CÓDIGO AÑADIDO] Backup y Restauración de Feeds
# ===================================================================
@app.route("/backup_feeds")
def backup_feeds():
"""Exporta todos los feeds a un archivo CSV."""
try:
with get_conn() as conn:
with conn.cursor(cursor_factory=psycopg2.extras.DictCursor) as cursor:
cursor.execute("""
SELECT f.id, f.nombre, f.descripcion, f.url, f.categoria_id, c.nombre AS categoria,
f.pais_id, p.nombre AS pais, f.idioma, f.activo, f.fallos
FROM feeds f
LEFT JOIN categorias c ON f.categoria_id = c.id
LEFT JOIN paises p ON f.pais_id = p.id
ORDER BY f.id
""")
feeds_ = cursor.fetchall()
if not feeds_:
flash("No hay feeds para exportar.", "warning")
return redirect(url_for("feeds"))
si = StringIO()
writer = csv.DictWriter(si, fieldnames=[desc[0] for desc in cursor.description])
writer.writeheader()
writer.writerows([dict(row) for row in feeds_])
output = si.getvalue()
si.close()
return Response(
output,
mimetype="text/csv",
headers={"Content-Disposition": "attachment;filename=feeds_backup.csv"},
)
except Exception as e:
app.logger.error(f"[ERROR] Al hacer backup de feeds: {e}", exc_info=True)
flash("Error al generar el backup.", "error")
return redirect(url_for("feeds"))
@app.route("/restore_feeds", methods=["GET", "POST"])
def restore_feeds():
"""Muestra el formulario de restauración y procesa el archivo CSV subido."""
if request.method == "POST":
file = request.files.get("file")
if not file or not file.filename.endswith(".csv"):
flash("Archivo no válido. Por favor, sube un archivo .csv.", "error")
return redirect(url_for("restore_feeds"))
try:
file_stream = StringIO(file.read().decode("utf-8"))
reader = csv.DictReader(file_stream)
rows = list(reader)
n_ok, n_err = 0, 0
with get_conn() as conn:
with conn.cursor() as cursor:
for row in rows:
try:
activo_val = str(row.get("activo", "")).strip().lower()
activo = activo_val in ["1", "true", "t", "yes", "on"]
cursor.execute(
"""
INSERT INTO feeds (id, nombre, descripcion, url, categoria_id, pais_id, idioma, activo, fallos)
VALUES (%(id)s, %(nombre)s, %(descripcion)s, %(url)s, %(categoria_id)s, %(pais_id)s, %(idioma)s, %(activo)s, %(fallos)s)
ON CONFLICT (id) DO UPDATE SET
nombre = EXCLUDED.nombre, descripcion = EXCLUDED.descripcion, url = EXCLUDED.url,
categoria_id = EXCLUDED.categoria_id, pais_id = EXCLUDED.pais_id, idioma = EXCLUDED.idioma,
activo = EXCLUDED.activo, fallos = EXCLUDED.fallos;
""",
{
"id": int(row.get("id")), "nombre": row.get("nombre"), "descripcion": row.get("descripcion") or "",
"url": row.get("url"), "categoria_id": int(row["categoria_id"]) if row.get("categoria_id") else None,
"pais_id": int(row["pais_id"]) if row.get("pais_id") else None, "idioma": row.get("idioma") or None,
"activo": activo, "fallos": int(row.get("fallos", 0)),
}
)
n_ok += 1
except Exception as e:
n_err += 1
app.logger.error(f"Error procesando fila del CSV: {row} - Error: {e}")
flash(f"Restauración completada. Feeds procesados: {n_ok}. Errores: {n_err}.", "success" if n_err == 0 else "warning")
except Exception as e:
app.logger.error(f"Error al restaurar feeds desde CSV: {e}", exc_info=True)
flash(f"Ocurrió un error general al procesar el archivo: {e}", "error")
return redirect(url_for("feeds"))
return render_template("restore_feeds.html")
# ===================================================================
# [FIN DEL CÓDIGO AÑADIDO]
# ===================================================================
# ================================ # ================================
# Lógica de procesado de feeds # Lógica de procesado de feeds
@ -234,28 +324,22 @@ def fetch_and_store():
with conn.cursor(cursor_factory=psycopg2.extras.DictCursor) as cursor: with conn.cursor(cursor_factory=psycopg2.extras.DictCursor) as cursor:
cursor.execute("SELECT id, url, categoria_id, pais_id FROM feeds WHERE activo = TRUE") cursor.execute("SELECT id, url, categoria_id, pais_id FROM feeds WHERE activo = TRUE")
feeds_to_process = cursor.fetchall() feeds_to_process = cursor.fetchall()
for feed in feeds_to_process: for feed in feeds_to_process:
try: try:
app.logger.info(f"Procesando feed: {feed['url']}") app.logger.info(f"Procesando feed: {feed['url']}")
parsed = feedparser.parse(feed['url']) parsed = feedparser.parse(feed['url'])
if getattr(parsed, "bozo", False): if getattr(parsed, "bozo", False):
app.logger.warning(f"[BOZO] Feed mal formado: {feed['url']}") app.logger.warning(f"[BOZO] Feed mal formado: {feed['url']}")
sumar_fallo_feed(cursor, feed['id']) sumar_fallo_feed(cursor, feed['id'])
continue continue
resetear_fallos_feed(cursor, feed['id']) resetear_fallos_feed(cursor, feed['id'])
for entry in parsed.entries: for entry in parsed.entries:
try: try:
link = entry.get("link") link = entry.get("link")
if not link: continue if not link: continue
noticia_id = hashlib.md5(link.encode()).hexdigest() noticia_id = hashlib.md5(link.encode()).hexdigest()
titulo = entry.get("title", "") titulo = entry.get("title", "")
resumen = entry.get("summary", "") resumen = entry.get("summary", "")
imagen_url = "" imagen_url = ""
if "media_content" in entry and entry.media_content: if "media_content" in entry and entry.media_content:
imagen_url = entry.media_content[0].get("url", "") imagen_url = entry.media_content[0].get("url", "")
@ -263,19 +347,13 @@ def fetch_and_store():
img_search = re.search(r'src="([^"]+)"', resumen) img_search = re.search(r'src="([^"]+)"', resumen)
if img_search: if img_search:
imagen_url = img_search.group(1) imagen_url = img_search.group(1)
fecha_publicacion = None fecha_publicacion = None
if "published_parsed" in entry: if "published_parsed" in entry:
fecha_publicacion = datetime(*entry.published_parsed[:6]) fecha_publicacion = datetime(*entry.published_parsed[:6])
elif "updated_parsed" in entry: elif "updated_parsed" in entry:
fecha_publicacion = datetime(*entry.updated_parsed[:6]) fecha_publicacion = datetime(*entry.updated_parsed[:6])
cursor.execute( cursor.execute(
""" "INSERT INTO noticias (id, titulo, resumen, url, fecha, imagen_url, categoria_id, pais_id) VALUES (%s, %s, %s, %s, %s, %s, %s, %s) ON CONFLICT (id) DO NOTHING",
INSERT INTO noticias (id, titulo, resumen, url, fecha, imagen_url, categoria_id, pais_id)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
ON CONFLICT (id) DO NOTHING
""",
(noticia_id, titulo, resumen, link, fecha_publicacion, imagen_url, feed['categoria_id'], feed['pais_id']) (noticia_id, titulo, resumen, link, fecha_publicacion, imagen_url, feed['categoria_id'], feed['pais_id'])
) )
except Exception as entry_err: except Exception as entry_err:
@ -283,25 +361,19 @@ def fetch_and_store():
except Exception as e: except Exception as e:
app.logger.error(f"[PARSE ERROR] En feed {feed['url']}: {e}", exc_info=True) app.logger.error(f"[PARSE ERROR] En feed {feed['url']}: {e}", exc_info=True)
sumar_fallo_feed(cursor, feed['id']) sumar_fallo_feed(cursor, feed['id'])
app.logger.info(f"Ciclo de feeds completado.") app.logger.info(f"Ciclo de feeds completado.")
except psycopg2.Error as db_err: except psycopg2.Error as db_err:
app.logger.error(f"[DB ERROR] Fallo en el ciclo de actualización de feeds: {db_err}", exc_info=True) app.logger.error(f"[DB ERROR] Fallo en el ciclo de actualización de feeds: {db_err}", exc_info=True)
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# Lanzador de la aplicación + scheduler # Lanzador de la aplicación + scheduler
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
if __name__ == "__main__": if __name__ == "__main__":
# Evita que el scheduler se inicie dos veces en modo debug con el re-cargador
if os.environ.get('WERKZEUG_RUN_MAIN') != 'true': if os.environ.get('WERKZEUG_RUN_MAIN') != 'true':
scheduler = BackgroundScheduler(daemon=True) scheduler = BackgroundScheduler(daemon=True)
scheduler.add_job(fetch_and_store, "interval", minutes=2, id="rss_job", misfire_grace_time=60) scheduler.add_job(fetch_and_store, "interval", minutes=2, id="rss_job", misfire_grace_time=60)
scheduler.start() scheduler.start()
app.logger.info("Scheduler iniciado correctamente.") app.logger.info("Scheduler iniciado correctamente.")
# Apagar el scheduler de forma limpia al salir
import atexit import atexit
atexit.register(lambda: scheduler.shutdown()) atexit.register(lambda: scheduler.shutdown())
app.run(host="0.0.0.0", port=5000, debug=True, use_reloader=True) app.run(host="0.0.0.0", port=5000, debug=True, use_reloader=True)