neo4j_driver.py 1003 B

1234567891011121314151617181920212223242526272829303132333435
  1. from flask import current_app
  2. from neo4j import GraphDatabase
  3. from neo4j.exceptions import ServiceUnavailable
  4. class Neo4jDriver:
  5. def __init__(self):
  6. self._driver = None
  7. def connect(self):
  8. if not self._driver:
  9. self._driver = GraphDatabase.driver(
  10. current_app.config['NEO4J_URI'],
  11. auth=(current_app.config['NEO4J_USER'], current_app.config['NEO4J_PASSWORD']),
  12. encrypted=current_app.config['NEO4J_ENCRYPTED']
  13. )
  14. return self._driver
  15. def close(self):
  16. if self._driver:
  17. self._driver.close()
  18. self._driver = None
  19. def verify_connectivity(self):
  20. try:
  21. self.connect().verify_connectivity()
  22. return True
  23. except ServiceUnavailable:
  24. return False
  25. def get_session(self):
  26. """获取 Neo4j 会话"""
  27. return self.connect().session()
  28. # 单例实例
  29. neo4j_driver = Neo4jDriver()