db_manager.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. """
  2. 数据库管理器
  3. 负责数据库连接及会话管理
  4. """
  5. from flask_sqlalchemy import SQLAlchemy
  6. from flask_migrate import Migrate
  7. import os
  8. # 初始化数据库对象
  9. db = SQLAlchemy()
  10. migrate = Migrate()
  11. def init_db(app):
  12. """
  13. 初始化数据库连接
  14. Args:
  15. app: Flask应用实例
  16. """
  17. # 确保数据目录存在
  18. data_dir = os.path.join(os.getcwd(), "data")
  19. if not os.path.exists(data_dir):
  20. os.makedirs(data_dir, exist_ok=True)
  21. # 设置数据库URI
  22. sqlite_path = os.path.join(data_dir, "financial_tools.db")
  23. app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{sqlite_path}'
  24. app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
  25. # 初始化SQLAlchemy和Migrate
  26. db.init_app(app)
  27. migrate.init_app(app, db)
  28. # 初始化数据库表结构和基础数据
  29. with app.app_context():
  30. from app.database.schema import create_schemas
  31. create_schemas(app)
  32. # 初始化trend_info表数据
  33. from app.database.init_trend_info import init_trend_info
  34. init_trend_info()
  35. return db
  36. def get_db():
  37. """
  38. 获取数据库实例
  39. Returns:
  40. SQLAlchemy实例
  41. """
  42. return db
  43. def close_db():
  44. """
  45. 关闭数据库连接
  46. """
  47. db.session.close()