external_api.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. import re
  2. import sys
  3. from flask import got_request_exception, current_app
  4. from flask_restful import Api, http_status_message
  5. from werkzeug.datastructures import Headers
  6. from werkzeug.exceptions import HTTPException
  7. class ExternalApi(Api):
  8. def handle_error(self, e):
  9. """Error handler for the API transforms a raised exception into a Flask
  10. response, with the appropriate HTTP status code and body.
  11. :param e: the raised Exception object
  12. :type e: Exception
  13. """
  14. got_request_exception.send(current_app, exception=e)
  15. headers = Headers()
  16. if isinstance(e, HTTPException):
  17. if e.response is not None:
  18. resp = e.get_response()
  19. return resp
  20. status_code = e.code
  21. default_data = {
  22. 'code': re.sub(r'(?<!^)(?=[A-Z])', '_', type(e).__name__).lower(),
  23. 'message': getattr(e, 'description', http_status_message(status_code)),
  24. 'status': status_code
  25. }
  26. headers = e.get_response().headers
  27. elif isinstance(e, ValueError):
  28. status_code = 400
  29. default_data = {
  30. 'code': 'invalid_param',
  31. 'message': str(e),
  32. 'status': status_code
  33. }
  34. else:
  35. status_code = 500
  36. default_data = {
  37. 'message': http_status_message(status_code),
  38. }
  39. # Werkzeug exceptions generate a content-length header which is added
  40. # to the response in addition to the actual content-length header
  41. # https://github.com/flask-restful/flask-restful/issues/534
  42. remove_headers = ('Content-Length',)
  43. for header in remove_headers:
  44. headers.pop(header, None)
  45. data = getattr(e, 'data', default_data)
  46. error_cls_name = type(e).__name__
  47. if error_cls_name in self.errors:
  48. custom_data = self.errors.get(error_cls_name, {})
  49. custom_data = custom_data.copy()
  50. status_code = custom_data.get('status', 500)
  51. if 'message' in custom_data:
  52. custom_data['message'] = custom_data['message'].format(
  53. message=str(e.description if hasattr(e, 'description') else e)
  54. )
  55. data.update(custom_data)
  56. # record the exception in the logs when we have a server error of status code: 500
  57. if status_code and status_code >= 500:
  58. exc_info = sys.exc_info()
  59. if exc_info[1] is None:
  60. exc_info = None
  61. current_app.log_exception(exc_info)
  62. if status_code == 406 and self.default_mediatype is None:
  63. # if we are handling NotAcceptable (406), make sure that
  64. # make_response uses a representation we support as the
  65. # default mediatype (so that make_response doesn't throw
  66. # another NotAcceptable error).
  67. supported_mediatypes = list(self.representations.keys()) # only supported application/json
  68. fallback_mediatype = supported_mediatypes[0] if supported_mediatypes else "text/plain"
  69. data = {
  70. 'code': 'not_acceptable',
  71. 'message': data.get('message')
  72. }
  73. resp = self.make_response(
  74. data,
  75. status_code,
  76. headers,
  77. fallback_mediatype = fallback_mediatype
  78. )
  79. elif status_code == 400:
  80. if isinstance(data.get('message'), dict):
  81. param_key, param_value = list(data.get('message').items())[0]
  82. data = {
  83. 'code': 'invalid_param',
  84. 'message': param_value,
  85. 'params': param_key
  86. }
  87. else:
  88. if 'code' not in data:
  89. data['code'] = 'unknown'
  90. resp = self.make_response(data, status_code, headers)
  91. else:
  92. if 'code' not in data:
  93. data['code'] = 'unknown'
  94. resp = self.make_response(data, status_code, headers)
  95. if status_code == 401:
  96. resp = self.unauthorized(resp)
  97. return resp