feat: Integración automática con Notion + análisis completo del código
- Instalado notion-client SDK oficial para integración robusta - Refactorizado services/notion_service.py con SDK oficial de Notion - Rate limiting con retry y exponential backoff - Parser Markdown → Notion blocks (headings, bullets, paragraphs) - Soporte para pages y databases - Manejo robusto de errores - Integración automática en document/generators.py - PDFs se suben automáticamente a Notion después de generarse - Contenido completo del resumen formateado con bloques - Metadata rica (tipo de archivo, path, fecha) - Configuración de Notion en main.py - Inicialización automática al arrancar el servicio - Validación de credenciales - Actualizado config/settings.py - Agregado load_dotenv() para cargar variables de .env - Configuración de Notion (NOTION_API, NOTION_DATABASE_ID) - Scripts de utilidad creados: - test_notion_integration.py: Test de subida a Notion - test_pipeline_notion.py: Test del pipeline completo - verify_notion_permissions.py: Verificación de permisos - list_notion_pages.py: Listar páginas accesibles - diagnose_notion.py: Diagnóstico completo - create_notion_database.py: Crear database automáticamente - restart_service.sh: Script de reinicio del servicio - Documentación completa en opus.md: - Análisis exhaustivo del codebase (42 archivos Python) - Bugs críticos identificados y soluciones - Mejoras de seguridad (autenticación, rate limiting, CORS, CSP) - Optimizaciones de rendimiento (Celery, Redis, PostgreSQL, WebSockets) - Plan de testing (estructura, ejemplos, 80% coverage goal) - Roadmap de implementación (6 sprints detallados) - Integración avanzada con Notion documentada Estado: Notion funcionando correctamente, PDFs se suben automáticamente
This commit is contained in:
95
verify_notion_permissions.py
Normal file
95
verify_notion_permissions.py
Normal file
@@ -0,0 +1,95 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Script para verificar y configurar permisos de Notion
|
||||
"""
|
||||
|
||||
import sys
|
||||
import logging
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).parent))
|
||||
|
||||
from config import settings
|
||||
from notion_client import Client
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(levelname)s - %(message)s")
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def main():
|
||||
print("\n" + "=" * 60)
|
||||
print("🔧 VERIFICACIÓN DE PERMISOS DE NOTION")
|
||||
print("=" * 60 + "\n")
|
||||
|
||||
# Configuración
|
||||
token = settings.NOTION_API_TOKEN
|
||||
database_id = settings.NOTION_DATABASE_ID
|
||||
|
||||
if not token or not database_id:
|
||||
print("❌ Falta configuración de Notion en .env")
|
||||
print(f" NOTION_API: {'✅' if token else '❌'}")
|
||||
print(f" NOTION_DATABASE_ID: {'✅' if database_id else '❌'}")
|
||||
return
|
||||
|
||||
print(f"✅ Token configurado: {token[:20]}...")
|
||||
print(f"✅ Database ID: {database_id}\n")
|
||||
|
||||
# Crear cliente
|
||||
client = Client(auth=token)
|
||||
|
||||
print("📋 PASOS PARA CONFIGURAR LOS PERMISOS:\n")
|
||||
print("1. Abre Notion y ve a tu base de datos 'CBC'")
|
||||
print(f" URL: https://www.notion.so/{database_id}")
|
||||
print("\n2. Click en los 3 puntos (⋯) en la esquina superior derecha")
|
||||
print("\n3. Selecciona 'Connections' o 'Añadir conexiones'")
|
||||
print("\n4. Busca tu integración y actívala")
|
||||
print(f" (Debería aparecer con el nombre que le pusiste)")
|
||||
print("\n5. Confirma los permisos\n")
|
||||
|
||||
print("-" * 60)
|
||||
print("\n🧪 Intentando conectar con Notion...\n")
|
||||
|
||||
try:
|
||||
# Intentar obtener la base de datos
|
||||
database = client.databases.retrieve(database_id=database_id)
|
||||
|
||||
print("✅ ¡ÉXITO! La integración puede acceder a la base de datos")
|
||||
print(f"\n📊 Información de la base de datos:")
|
||||
print(
|
||||
f" Título: {database['title'][0]['plain_text'] if database.get('title') else 'Sin título'}"
|
||||
)
|
||||
print(f" ID: {database['id']}")
|
||||
print(f"\n Propiedades disponibles:")
|
||||
|
||||
for prop_name, prop_data in database.get("properties", {}).items():
|
||||
prop_type = prop_data.get("type", "unknown")
|
||||
print(f" - {prop_name}: {prop_type}")
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("✅ TODO CONFIGURADO CORRECTAMENTE")
|
||||
print("=" * 60 + "\n")
|
||||
|
||||
print("🚀 Ahora ejecuta: python test_notion_integration.py")
|
||||
print(" para probar subir un documento\n")
|
||||
|
||||
except Exception as e:
|
||||
error_msg = str(e)
|
||||
|
||||
print("❌ ERROR AL CONECTAR CON NOTION\n")
|
||||
print(f"Error: {error_msg}\n")
|
||||
|
||||
if "Could not find database" in error_msg:
|
||||
print("⚠️ LA BASE DE DATOS NO ESTÁ COMPARTIDA CON TU INTEGRACIÓN")
|
||||
print("\nSigue los pasos arriba para compartir la base de datos.")
|
||||
elif "Unauthorized" in error_msg or "401" in error_msg:
|
||||
print("⚠️ EL TOKEN DE API ES INVÁLIDO")
|
||||
print("\nVerifica que el token esté correcto en .env")
|
||||
else:
|
||||
print("⚠️ ERROR DESCONOCIDO")
|
||||
print(f"\nDetalles: {error_msg}")
|
||||
|
||||
print("\n" + "=" * 60 + "\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user