Spaces:
Sleeping
Sleeping
| # 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) ... |