factory.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. """
  2. 应用工厂:创建和配置 FastAPI 应用实例。
  3. """
  4. import redis
  5. from fastapi import FastAPI
  6. from views import lifespan
  7. from foundation.infrastructure.config.config import config_handler
  8. from server.celery_manager import CeleryWorkerManager
  9. class ServerUtils:
  10. """Redis 连接工具。"""
  11. @staticmethod
  12. def get_redis_connection():
  13. redis_host = config_handler.get('redis', 'REDIS_HOST', 'localhost')
  14. redis_port = config_handler.get('redis', 'REDIS_PORT', '6379')
  15. redis_password = config_handler.get('redis', 'REDIS_PASSWORD', '')
  16. redis_db = config_handler.get('redis', 'REDIS_DB', '0')
  17. if redis_password:
  18. redis_url = f'redis://:{redis_password}@{redis_host}:{redis_port}/{redis_db}'
  19. else:
  20. redis_url = f'redis://{redis_host}:{redis_port}/{redis_db}'
  21. return redis.from_url(redis_url, decode_responses=True)
  22. class ApplicationFactory:
  23. """应用工厂。"""
  24. def __init__(self):
  25. self.server_utils = ServerUtils()
  26. self.celery_manager = CeleryWorkerManager(self.server_utils)
  27. def create_app(self) -> FastAPI:
  28. from server.routes import register_routes
  29. app = FastAPI(
  30. title="Agent API - 施工方案审查系统",
  31. version="0.3",
  32. description="Agent API - 集成施工方案审查功能",
  33. lifespan=lifespan,
  34. )
  35. register_routes(app)
  36. return app
  37. def create_server_config(self) -> dict:
  38. port = config_handler.get('launch', 'LAUNCH_PORT', 8002)
  39. try:
  40. port = int(port)
  41. except (ValueError, TypeError):
  42. port = 8002
  43. return {
  44. 'host': config_handler.get('launch', 'HOST', '0.0.0.0'),
  45. 'port': port,
  46. 'reload': False,
  47. 'with_celery': True,
  48. }