Spaces:
Sleeping
Sleeping
File size: 2,357 Bytes
58de15f |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
# app/utils/neo4j_utils.py (Corrected Import)
import logging
# --- MODIFICATION HERE ---
# Import base components from neo4j
from neo4j import AsyncGraphDatabase, AsyncDriver
# Import specific error class from neo4j.exceptions
from neo4j.exceptions import Neo4jError
# --- END MODIFICATION ---
from typing import Optional
# Import settings for credentials
from app.core.config import settings
logger = logging.getLogger(__name__)
# Global variable to hold the driver instance (singleton pattern)
_driver: Optional[AsyncDriver] = None
async def get_driver() -> Optional[AsyncDriver]:
"""
Initializes and returns the singleton Neo4j AsyncDriver instance.
Reads credentials from settings. Returns None on failure.
"""
global _driver
if _driver is None:
uri = settings.NEO4J_URI
username = settings.NEO4J_USERNAME
password = settings.NEO4J_PASSWORD
if not uri or not username or not password:
logger.error("Neo4j connection details (URI, USERNAME, PASSWORD) missing in configuration.")
return None
logger.info(f"Initializing Neo4j Async Driver for URI: {uri}")
try:
_driver = AsyncGraphDatabase.driver(uri, auth=(username, password))
await _driver.verify_connectivity()
logger.info("Neo4j Driver initialized and connection verified.")
# --- MODIFICATION HERE: Catch the correctly imported Neo4jError ---
except Neo4jError as e:
# --- END MODIFICATION ---
logger.exception(f"Failed to initialize Neo4j Driver or verify connection: {e.message} (code: {e.code})")
_driver = None
except Exception as e:
logger.exception(f"An unexpected error occurred during Neo4j Driver initialization: {e}")
_driver = None
return _driver
async def close_driver():
"""Closes the Neo4j AsyncDriver connection if it exists."""
global _driver
if _driver is not None:
logger.info("Closing Neo4j Async Driver...")
try:
await _driver.close()
_driver = None
logger.info("Neo4j Driver closed successfully.")
except Exception as e:
logger.exception(f"Error closing Neo4j Driver: {e}")
# Optional: Dependency for API endpoints if needed later
# ... (keep commented out for now) ... |