Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

external_api.py 4.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. import re
  2. import sys
  3. from collections.abc import Mapping
  4. from typing import Any
  5. from flask import Blueprint, Flask, current_app, got_request_exception
  6. from flask_restx import Api
  7. from werkzeug.exceptions import HTTPException
  8. from werkzeug.http import HTTP_STATUS_CODES
  9. from configs import dify_config
  10. from core.errors.error import AppInvokeQuotaExceededError
  11. def http_status_message(code):
  12. return HTTP_STATUS_CODES.get(code, "")
  13. def register_external_error_handlers(api: Api):
  14. @api.errorhandler(HTTPException)
  15. def handle_http_exception(e: HTTPException):
  16. got_request_exception.send(current_app, exception=e)
  17. # If Werkzeug already prepared a Response, just use it.
  18. if getattr(e, "response", None) is not None:
  19. return e.response
  20. status_code = getattr(e, "code", 500) or 500
  21. # Build a safe, dict-like payload
  22. default_data = {
  23. "code": re.sub(r"(?<!^)(?=[A-Z])", "_", type(e).__name__).lower(),
  24. "message": getattr(e, "description", http_status_message(status_code)),
  25. "status": status_code,
  26. }
  27. if default_data["message"] == "Failed to decode JSON object: Expecting value: line 1 column 1 (char 0)":
  28. default_data["message"] = "Invalid JSON payload received or JSON payload is empty."
  29. # Use headers on the exception if present; otherwise none.
  30. headers = {}
  31. exc_headers = getattr(e, "headers", None)
  32. if exc_headers:
  33. headers.update(exc_headers)
  34. # Payload per status
  35. if status_code == 406 and api.default_mediatype is None:
  36. data = {"code": "not_acceptable", "message": default_data["message"], "status": status_code}
  37. return data, status_code, headers
  38. elif status_code == 400:
  39. msg = default_data["message"]
  40. if isinstance(msg, Mapping) and msg:
  41. # Convert param errors like {"field": "reason"} into a friendly shape
  42. param_key, param_value = next(iter(msg.items()))
  43. data = {
  44. "code": "invalid_param",
  45. "message": str(param_value),
  46. "params": param_key,
  47. "status": status_code,
  48. }
  49. else:
  50. data = {**default_data}
  51. data.setdefault("code", "unknown")
  52. return data, status_code, headers
  53. else:
  54. data = {**default_data}
  55. data.setdefault("code", "unknown")
  56. # If you need WWW-Authenticate for 401, add it to headers
  57. if status_code == 401:
  58. headers["WWW-Authenticate"] = 'Bearer realm="api"'
  59. return data, status_code, headers
  60. _ = handle_http_exception
  61. @api.errorhandler(ValueError)
  62. def handle_value_error(e: ValueError):
  63. got_request_exception.send(current_app, exception=e)
  64. status_code = 400
  65. data = {"code": "invalid_param", "message": str(e), "status": status_code}
  66. return data, status_code
  67. _ = handle_value_error
  68. @api.errorhandler(AppInvokeQuotaExceededError)
  69. def handle_quota_exceeded(e: AppInvokeQuotaExceededError):
  70. got_request_exception.send(current_app, exception=e)
  71. status_code = 429
  72. data = {"code": "too_many_requests", "message": str(e), "status": status_code}
  73. return data, status_code
  74. _ = handle_quota_exceeded
  75. @api.errorhandler(Exception)
  76. def handle_general_exception(e: Exception):
  77. got_request_exception.send(current_app, exception=e)
  78. status_code = 500
  79. data = getattr(e, "data", {"message": http_status_message(status_code)})
  80. # 🔒 Normalize non-mapping data (e.g., if someone set e.data = Response)
  81. if not isinstance(data, dict):
  82. data = {"message": str(e)}
  83. data.setdefault("code", "unknown")
  84. data.setdefault("status", status_code)
  85. # Log stack
  86. exc_info: Any = sys.exc_info()
  87. if exc_info[1] is None:
  88. exc_info = None
  89. current_app.log_exception(exc_info)
  90. return data, status_code
  91. _ = handle_general_exception
  92. class ExternalApi(Api):
  93. _authorizations = {
  94. "Bearer": {
  95. "type": "apiKey",
  96. "in": "header",
  97. "name": "Authorization",
  98. "description": "Type: Bearer {your-api-key}",
  99. }
  100. }
  101. def __init__(self, app: Blueprint | Flask, *args, **kwargs):
  102. kwargs.setdefault("authorizations", self._authorizations)
  103. kwargs.setdefault("security", "Bearer")
  104. kwargs["add_specs"] = dify_config.SWAGGER_UI_ENABLED
  105. kwargs["doc"] = dify_config.SWAGGER_UI_PATH if dify_config.SWAGGER_UI_ENABLED else False
  106. # manual separate call on construction and init_app to ensure configs in kwargs effective
  107. super().__init__(app=None, *args, **kwargs) # type: ignore
  108. self.init_app(app, **kwargs)
  109. register_external_error_handlers(self)