mongodb
Signed-off-by: Omar Sánchez Pizarro <omar.sanchez@pistacero.net>
This commit is contained in:
@@ -1,8 +1,10 @@
|
||||
import logging
|
||||
import redis
|
||||
import json
|
||||
|
||||
NOTIFIED_ARTICLE_TTL = 7 * 24 * 60 * 60 # TTL de 7 días en segundos para artículos notificados
|
||||
# Importar MongoDBArticleCache desde mongodb_manager
|
||||
from managers.mongodb_manager import MongoDBArticleCache
|
||||
|
||||
NOTIFIED_ARTICLE_TTL = 7 * 24 * 60 * 60 # TTL de 7 días en segundos para artículos notificados (mantener para compatibilidad)
|
||||
|
||||
class RedisArticleCache:
|
||||
"""Maneja el cache de artículos notificados usando Redis"""
|
||||
@@ -45,21 +47,29 @@ class RedisArticleCache:
|
||||
self.logger.error(f"Error verificando artículo en Redis: {e}")
|
||||
return False
|
||||
|
||||
def mark_article_as_notified(self, article):
|
||||
def mark_article_as_notified(self, article, username=None, worker_name=None):
|
||||
"""Marca un artículo como notificado en Redis con TTL, guardando toda la información del artículo"""
|
||||
try:
|
||||
key = self._get_article_key(article)
|
||||
# Guardar toda la información del artículo como JSON
|
||||
# Verificar si el artículo ya existe para mantener el estado de favorito
|
||||
# Verificar si el artículo ya existe para mantener el estado de favorito, username y worker_name
|
||||
existing_value = self._redis_client.get(key)
|
||||
is_favorite = False
|
||||
existing_username = None
|
||||
existing_worker_name = None
|
||||
if existing_value:
|
||||
try:
|
||||
existing_data = json.loads(existing_value)
|
||||
is_favorite = existing_data.get('is_favorite', False)
|
||||
existing_username = existing_data.get('username')
|
||||
existing_worker_name = existing_data.get('worker_name')
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
|
||||
# Mantener username y worker_name existentes si ya existen, o usar los nuevos si se proporcionan
|
||||
final_username = existing_username if existing_username else username
|
||||
final_worker_name = existing_worker_name if existing_worker_name else worker_name
|
||||
|
||||
article_data = {
|
||||
'id': article.get_id(),
|
||||
'title': article.get_title(),
|
||||
@@ -74,11 +84,18 @@ class RedisArticleCache:
|
||||
'platform': article.get_platform(),
|
||||
'is_favorite': is_favorite, # Mantener el estado de favorito
|
||||
}
|
||||
|
||||
# Añadir username y worker_name si están disponibles
|
||||
if final_username:
|
||||
article_data['username'] = final_username
|
||||
if final_worker_name:
|
||||
article_data['worker_name'] = final_worker_name
|
||||
|
||||
self._redis_client.setex(key, NOTIFIED_ARTICLE_TTL, json.dumps(article_data))
|
||||
except Exception as e:
|
||||
self.logger.error(f"Error marcando artículo como notificado en Redis: {e}")
|
||||
|
||||
def mark_articles_as_notified(self, articles):
|
||||
def mark_articles_as_notified(self, articles, username=None, worker_name=None):
|
||||
"""Añade múltiples artículos a la lista de artículos ya notificados en Redis"""
|
||||
article_list = articles if isinstance(articles, list) else [articles]
|
||||
|
||||
@@ -122,6 +139,13 @@ class RedisArticleCache:
|
||||
'platform': article.get_platform(),
|
||||
'is_favorite': False, # Por defecto no es favorito
|
||||
}
|
||||
|
||||
# Añadir username y worker_name si están disponibles
|
||||
if username:
|
||||
article_data['username'] = username
|
||||
if worker_name:
|
||||
article_data['worker_name'] = worker_name
|
||||
|
||||
pipe.setex(key, NOTIFIED_ARTICLE_TTL, json.dumps(article_data))
|
||||
added_count += 1
|
||||
|
||||
@@ -209,28 +233,35 @@ class RedisArticleCache:
|
||||
return 0
|
||||
|
||||
|
||||
def create_article_cache(cache_type='redis', **kwargs):
|
||||
def create_article_cache(cache_type='mongodb', **kwargs):
|
||||
"""
|
||||
Factory function para crear el cache de artículos usando Redis.
|
||||
Factory function para crear el cache de artículos usando MongoDB.
|
||||
|
||||
Args:
|
||||
cache_type: 'redis' (solo Redis está soportado)
|
||||
**kwargs: Argumentos para Redis:
|
||||
- redis_host: host de Redis (default: 'localhost')
|
||||
- redis_port: puerto de Redis (default: 6379)
|
||||
- redis_db: base de datos de Redis (default: 0)
|
||||
- redis_password: contraseña de Redis (opcional)
|
||||
cache_type: 'mongodb' (solo MongoDB está soportado)
|
||||
**kwargs: Argumentos para MongoDB:
|
||||
- mongodb_host: host de MongoDB (default: 'localhost')
|
||||
- mongodb_port: puerto de MongoDB (default: 27017)
|
||||
- mongodb_database: base de datos (default: 'wallabicher')
|
||||
- mongodb_username: usuario de MongoDB (opcional)
|
||||
- mongodb_password: contraseña de MongoDB (opcional)
|
||||
- mongodb_auth_source: base de datos para autenticación (default: 'admin')
|
||||
|
||||
Returns:
|
||||
RedisArticleCache
|
||||
MongoDBArticleCache
|
||||
"""
|
||||
if cache_type != 'redis':
|
||||
raise ValueError(f"Tipo de cache desconocido: {cache_type}. Solo se soporta 'redis'")
|
||||
|
||||
return RedisArticleCache(
|
||||
redis_host=kwargs.get('redis_host', 'localhost'),
|
||||
redis_port=kwargs.get('redis_port', 6379),
|
||||
redis_db=kwargs.get('redis_db', 0),
|
||||
redis_password=kwargs.get('redis_password')
|
||||
)
|
||||
if cache_type == 'mongodb':
|
||||
return MongoDBArticleCache(
|
||||
mongodb_host=kwargs.get('mongodb_host', 'localhost'),
|
||||
mongodb_port=kwargs.get('mongodb_port', 27017),
|
||||
mongodb_database=kwargs.get('mongodb_database', 'wallabicher'),
|
||||
mongodb_username=kwargs.get('mongodb_username'),
|
||||
mongodb_password=kwargs.get('mongodb_password'),
|
||||
mongodb_auth_source=kwargs.get('mongodb_auth_source', 'admin')
|
||||
)
|
||||
elif cache_type == 'redis':
|
||||
# Mantener compatibilidad con Redis (deprecated)
|
||||
raise ValueError("Redis ya no está soportado. Por favor, usa MongoDB.")
|
||||
else:
|
||||
raise ValueError(f"Tipo de cache desconocido: {cache_type}. Solo se soporta 'mongodb'")
|
||||
|
||||
|
||||
Reference in New Issue
Block a user