app.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. """Application factory."""
  2. from flask import Flask
  3. from app.config.setting import config
  4. from app.extensions import db
  5. def register_blueprints(app):
  6. """Register all application blueprints."""
  7. from app.api.v1 import create_blueprint_v1
  8. from app.routes.health import bp as health_bp
  9. # API v1 under /v1
  10. app.register_blueprint(create_blueprint_v1(), url_prefix="/v1")
  11. # Health endpoint at /health
  12. app.register_blueprint(health_bp)
  13. def create_app(env: str = "default"):
  14. """Create and configure the Flask application."""
  15. app = Flask(__name__)
  16. app.config.from_object(config[env])
  17. # initialize extensions
  18. db.init_app(app)
  19. # optional: initialize logging and other extensions here
  20. try:
  21. from app.utils.logger import setup_logging
  22. setup_logging(app)
  23. except Exception:
  24. # keep app creation robust even if logging setup fails
  25. pass
  26. register_blueprints(app)
  27. # Register a global handler to convert APIException instances into JSON responses
  28. try:
  29. from app.exceptions.api_exception import APIException
  30. @app.errorhandler(APIException)
  31. def handle_api_exception(error):
  32. # HTTPException.get_response builds a Response object using get_body/get_headers
  33. response = error.get_response()
  34. return response
  35. except Exception:
  36. pass
  37. return app