app.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. app.logger.info("Application initialized in %s mode", env)
  24. except Exception:
  25. # keep app creation robust even if logging setup fails
  26. pass
  27. register_blueprints(app)
  28. # Register a global handler to convert APIException instances into JSON responses
  29. try:
  30. from app.exceptions.api_exception import APIException
  31. @app.errorhandler(APIException)
  32. def handle_api_exception(error):
  33. # HTTPException.get_response builds a Response object using get_body/get_headers
  34. response = error.get_response()
  35. return response
  36. except Exception:
  37. pass
  38. return app