corregido algunos errores internos

This commit is contained in:
jlimolina 2025-06-08 22:32:49 +00:00
parent 4ea56f3247
commit e355003f65
3 changed files with 29 additions and 14 deletions

View file

@ -1,7 +1,7 @@
#!/bin/bash #!/bin/bash
# Script de instalación completo y robusto para el Agregador RSS. # Script de instalación completo y robusto para el Agregador RSS.
# Instala y configura PostgreSQL, Python, y la aplicación como un servicio systemd. # Instala y configura PostgreSQL, Python, y la aplicación como un servicio systemd usando Waitress.
set -e set -e
@ -16,7 +16,7 @@ APP_USER="x" # El usuario no-root que ejecutará la aplicación.
APP_DIR="/home/$APP_USER/$APP_NAME" APP_DIR="/home/$APP_USER/$APP_NAME"
PYTHON_ENV="$APP_DIR/venv" PYTHON_ENV="$APP_DIR/venv"
SERVICE_FILE="/etc/systemd/system/$APP_NAME.service" SERVICE_FILE="/etc/systemd/system/$APP_NAME.service"
FLASK_APP_ENTRY="app:app" # Formato para Gunicorn: "nombre_fichero:nombre_variable_app" WSGI_APP_ENTRY="app:app" # Formato para Waitress/Gunicorn: "nombre_fichero:nombre_variable_app"
# ========= 1. INSTALAR DEPENDENCIAS DEL SISTEMA ========= # ========= 1. INSTALAR DEPENDENCIAS DEL SISTEMA =========
echo "🟢 Instalando dependencias del sistema (PostgreSQL, Python, etc.)..." echo "🟢 Instalando dependencias del sistema (PostgreSQL, Python, etc.)..."
@ -46,8 +46,8 @@ else
echo "✅ Base de datos '$DB_NAME' ya existe." echo "✅ Base de datos '$DB_NAME' ya existe."
fi fi
# ========= 3. CREAR TABLAS DE LA APLICACIÓN ========= # ========= 3. CREAR TABLAS CON RESTRICCIONES 'UNIQUE' =========
echo "📐 Creando tablas en la base de datos (si no existen)..." echo "📐 Creando tablas con protección anti-duplicados..."
export PGPASSWORD="$DB_PASS" export PGPASSWORD="$DB_PASS"
psql -U "$DB_USER" -h localhost -d "$DB_NAME" <<EOF psql -U "$DB_USER" -h localhost -d "$DB_NAME" <<EOF
CREATE TABLE IF NOT EXISTS continentes (id SERIAL PRIMARY KEY, nombre VARCHAR(50) NOT NULL UNIQUE); CREATE TABLE IF NOT EXISTS continentes (id SERIAL PRIMARY KEY, nombre VARCHAR(50) NOT NULL UNIQUE);
@ -60,11 +60,14 @@ unset PGPASSWORD
echo "✅ Tablas creadas/verificadas." echo "✅ Tablas creadas/verificadas."
# ========= 4. INSERTAR DATOS INICIALES (OPCIONAL) ========= # ========= 4. INSERTAR DATOS INICIALES (OPCIONAL) =========
# Nota: Si se ejecuta el script de nuevo, los INSERT darán un error de "violación de unicidad"
# y no se insertarán duplicados, lo cual es el comportamiento deseado.
for sql_file in continentes.sql paises.sql categorias.sql; do for sql_file in continentes.sql paises.sql categorias.sql; do
if [ -f "$APP_DIR/$sql_file" ]; then if [ -f "$APP_DIR/$sql_file" ]; then
echo "🗂️ Insertando datos desde $sql_file..." echo "🗂️ Insertando datos desde $sql_file..."
export PGPASSWORD="$DB_PASS" export PGPASSWORD="$DB_PASS"
psql -U "$DB_USER" -h localhost -d "$DB_NAME" -f "$APP_DIR/$sql_file" # El '|| true' al final evita que el script se detenga si los datos ya existen
psql -U "$DB_USER" -h localhost -d "$DB_NAME" -f "$APP_DIR/$sql_file" || true
unset PGPASSWORD unset PGPASSWORD
else else
echo "⚠️ Archivo de datos iniciales no encontrado, omitiendo: $sql_file" echo "⚠️ Archivo de datos iniciales no encontrado, omitiendo: $sql_file"
@ -76,27 +79,26 @@ echo "🐍 Creando entorno virtual en $PYTHON_ENV"
python3 -m venv "$PYTHON_ENV" python3 -m venv "$PYTHON_ENV"
echo "📦 Instalando dependencias desde requirements.txt..." echo "📦 Instalando dependencias desde requirements.txt..."
# Usamos el python del venv para ejecutar pip
"$PYTHON_ENV/bin/python" -m pip install --upgrade pip "$PYTHON_ENV/bin/python" -m pip install --upgrade pip
"$PYTHON_ENV/bin/python" -m pip install -r "$APP_DIR/requirements.txt" "$PYTHON_ENV/bin/python" -m pip install -r "$APP_DIR/requirements.txt"
# ========= 6. CREAR SERVICIO SYSTEMD ========= # ========= 6. CREAR SERVICIO SYSTEMD (CON WAITRESS) =========
echo "⚙️ Creando servicio systemd en: $SERVICE_FILE" echo "⚙️ Creando servicio systemd con Waitress..."
sudo tee "$SERVICE_FILE" > /dev/null <<EOF sudo tee "$SERVICE_FILE" > /dev/null <<EOF
[Unit] [Unit]
Description=Servicio del Agregador RSS de Noticias (Simple) Description=Servicio del Agregador RSS (con Waitress)
After=network.target postgresql.service After=network.target postgresql.service
Requires=postgresql.service Requires=postgresql.service
[Service] [Service]
# Mejora de seguridad: Ejecutar como usuario no-root. # Ejecutar como un usuario normal por seguridad
User=$APP_USER User=$APP_USER
Group=$APP_USER Group=$APP_USER
WorkingDirectory=$APP_DIR WorkingDirectory=$APP_DIR
# Comando final: Usa gunicorn, escucha en el puerto 8000, y tiene un timeout extendido. # Comando final: Usa Waitress, un servidor simple y eficiente sin workers.
ExecStart=$PYTHON_ENV/bin/gunicorn --bind 0.0.0.0:8000 --timeout 120 $FLASK_APP_ENTRY ExecStart=$PYTHON_ENV/bin/waitress-serve --host 0.0.0.0 --port 8000 $WSGI_APP_ENTRY
Restart=always Restart=always
Environment="PYTHONUNBUFFERED=1" Environment="PYTHONUNBUFFERED=1"
@ -109,8 +111,6 @@ EOF
echo "🚀 Recargando systemd y activando el servicio '$APP_NAME'..." echo "🚀 Recargando systemd y activando el servicio '$APP_NAME'..."
sudo systemctl daemon-reload sudo systemctl daemon-reload
sudo systemctl enable --now "$APP_NAME" sudo systemctl enable --now "$APP_NAME"
# --now hace start, pero un restart explícito asegura que usa la última conf.
sudo systemctl restart "$APP_NAME" sudo systemctl restart "$APP_NAME"
# ========= ESTADO FINAL ========= # ========= ESTADO FINAL =========

14
n Normal file
View file

@ -0,0 +1,14 @@
fecha | titulo | url
---------------------+-----------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------
2025-06-08 21:55:11 | Deportees Lawyers Push for Contempt Proceedings Despite His Return | https://www.nytimes.com/2025/06/08/us/politics/abrego-garcia-justice-department-contempt-proceedings.html
2025-06-08 21:51:57 | Степашин рассказал о стратегической ошибке в отношении Украины в 1990-х годах | https://rg.ru/2025/06/09/stepashin-rasskazal-o-strategicheskoj-oshibke-v-otnoshenii-ukrainy-v-1990-h-godah.html
2025-06-08 21:50:46 | Lavrov, Rubio in touch, keen to maintain ties — MFA | https://tass.com/politics/1970525
2025-06-08 21:45:00 | Минобороны РФ сообщило об уничтожении 24 украинских дронов | https://www.interfax.ru/russia/1030308
2025-06-08 21:39:46 | Cuts to UKs global vaccination funding would risk avoidable child deaths, experts warn | https://www.theguardian.com/society/2025/jun/08/global-vaccination-funding-cuts-threaten-uk-soft-power-and-pandemic-resilience
2025-06-08 21:32:32 | Крупный пожар в Подмосковье остановил движение на двух шоссе | https://rg.ru/2025/06/09/reg-cfo/dymovaia-zavesa.html
2025-06-08 21:31:06 | Zelensky declines 6,000 bodies to conceal army losses — envoy | https://tass.com/politics/1970521
2025-06-08 21:26:37 | Котяков и Ракова посетили геронтопсихологический центр в Москве | https://rg.ru/2025/06/09/reg-cfo/dom-s-teplom.html
2025-06-08 21:25:19 | Рогов: В оккупированном ВСУ городе Запорожье слышны взрывы и стрельба | https://rg.ru/2025/06/09/reg-zaporozhskaya/rogov-v-okkupirovannom-vsu-gorode-zaporozhe-slyshny-vzryvy-i-strelba.html
2025-06-08 21:23:00 | РФ готова поставлять Индонезии подлодки, корабли, истребители и системы ПВО | https://www.interfax.ru/world/1030307
(10 filas)

View file

@ -4,3 +4,4 @@ APScheduler==3.10.4
psycopg2-binary==2.9.10 psycopg2-binary==2.9.10
bleach==6.1.0 bleach==6.1.0
gunicorn==22.0.0 gunicorn==22.0.0
waitress