- 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
135 lines
4.8 KiB
Python
135 lines
4.8 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
Script para listar todas las páginas y bases de datos accesibles
|
|
"""
|
|
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
sys.path.insert(0, str(Path(__file__).parent))
|
|
|
|
from config import settings
|
|
from notion_client import Client
|
|
|
|
|
|
def main():
|
|
print("\n" + "=" * 70)
|
|
print("📚 LISTANDO TODAS LAS PÁGINAS Y BASES DE DATOS")
|
|
print("=" * 70 + "\n")
|
|
|
|
token = settings.NOTION_API_TOKEN
|
|
client = Client(auth=token)
|
|
|
|
try:
|
|
# Buscar todas las páginas sin filtro
|
|
print("🔍 Buscando todas las páginas accesibles...\n")
|
|
results = client.search(page_size=100)
|
|
|
|
all_items = results.get("results", [])
|
|
|
|
# Separar bases de datos y páginas
|
|
databases = [item for item in all_items if item.get("object") == "database"]
|
|
pages = [item for item in all_items if item.get("object") == "page"]
|
|
|
|
print(
|
|
f"✅ Encontrados: {len(databases)} base(s) de datos y {len(pages)} página(s)\n"
|
|
)
|
|
|
|
if databases:
|
|
print("=" * 70)
|
|
print("📊 BASES DE DATOS ENCONTRADAS:")
|
|
print("=" * 70)
|
|
|
|
for i, db in enumerate(databases, 1):
|
|
db_id = db.get("id", "N/A")
|
|
title_list = db.get("title", [])
|
|
title = (
|
|
title_list[0].get("plain_text", "Sin título")
|
|
if title_list
|
|
else "Sin título"
|
|
)
|
|
|
|
print(f"\n🔷 {i}. {title}")
|
|
print(f" ID: {db_id}")
|
|
print(f" URL: https://notion.so/{db_id.replace('-', '')}")
|
|
|
|
# Mostrar propiedades
|
|
props = db.get("properties", {})
|
|
if props:
|
|
print(f" Propiedades:")
|
|
for prop_name, prop_data in list(props.items())[:5]:
|
|
prop_type = prop_data.get("type", "unknown")
|
|
print(f" • {prop_name} ({prop_type})")
|
|
if len(props) > 5:
|
|
print(f" ... y {len(props) - 5} más")
|
|
|
|
print("-" * 70)
|
|
|
|
if pages:
|
|
print("\n" + "=" * 70)
|
|
print("📄 PÁGINAS ENCONTRADAS:")
|
|
print("=" * 70)
|
|
|
|
for i, page in enumerate(pages, 1):
|
|
page_id = page.get("id", "N/A")
|
|
|
|
# Intentar obtener el título
|
|
title = "Sin título"
|
|
props = page.get("properties", {})
|
|
|
|
# Buscar en diferentes ubicaciones del título
|
|
if "title" in props:
|
|
title_prop = props["title"]
|
|
if "title" in title_prop:
|
|
title_list = title_prop["title"]
|
|
if title_list:
|
|
title = title_list[0].get("plain_text", "Sin título")
|
|
elif "Name" in props:
|
|
name_prop = props["Name"]
|
|
if "title" in name_prop:
|
|
title_list = name_prop["title"]
|
|
if title_list:
|
|
title = title_list[0].get("plain_text", "Sin título")
|
|
|
|
print(f"\n🔷 {i}. {title}")
|
|
print(f" ID: {page_id}")
|
|
print(f" URL: https://notion.so/{page_id.replace('-', '')}")
|
|
print("-" * 70)
|
|
|
|
if databases:
|
|
print("\n" + "=" * 70)
|
|
print("💡 SIGUIENTE PASO:")
|
|
print("=" * 70)
|
|
print("\nSi 'CBC' aparece arriba como BASE DE DATOS:")
|
|
print("1. Copia el ID de la base de datos 'CBC'")
|
|
print("2. Actualiza tu .env:")
|
|
print(" NOTION_DATABASE_ID=<el_id_completo>")
|
|
print("\nSi 'CBC' aparece como PÁGINA:")
|
|
print("1. Abre la página en Notion")
|
|
print("2. Busca una base de datos dentro de esa página")
|
|
print("3. Haz click en '...' de la base de datos")
|
|
print("4. Selecciona 'Copy link to view'")
|
|
print("5. El ID estará en el URL copiado")
|
|
print("\n4. Ejecuta: python test_notion_integration.py\n")
|
|
else:
|
|
print("\n⚠️ No se encontraron bases de datos accesibles.")
|
|
print("\n📋 OPCIONES:")
|
|
print("\n1. Crear una nueva base de datos:")
|
|
print(" - Abre una de las páginas listadas arriba")
|
|
print(" - Crea una tabla/database dentro")
|
|
print(" - Copia el ID de esa base de datos")
|
|
print("\n2. O comparte una base de datos existente:")
|
|
print(" - Abre tu base de datos 'CBC' en Notion")
|
|
print(" - Click en '...' > 'Connections'")
|
|
print(" - Agrega tu integración\n")
|
|
|
|
except Exception as e:
|
|
print(f"❌ Error: {e}\n")
|
|
import traceback
|
|
|
|
traceback.print_exc()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|