external_api.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. import re
  2. import sys
  3. from flask import current_app, got_request_exception
  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. if default_data['message'] and default_data['message'] == 'Failed to decode JSON object: Expecting value: line 1 column 1 (char 0)':
  27. default_data['message'] = 'Invalid JSON payload received or JSON payload is empty.'
  28. headers = e.get_response().headers
  29. elif isinstance(e, ValueError):
  30. status_code = 400
  31. default_data = {
  32. 'code': 'invalid_param',
  33. 'message': str(e),
  34. 'status': status_code
  35. }
  36. else:
  37. status_code = 500
  38. default_data = {
  39. 'message': http_status_message(status_code),
  40. }
  41. # Werkzeug exceptions generate a content-length header which is added
  42. # to the response in addition to the actual content-length header
  43. # https://github.com/flask-restful/flask-restful/issues/534
  44. remove_headers = ('Content-Length',)
  45. for header in remove_headers:
  46. headers.pop(header, None)
  47. data = getattr(e, 'data', default_data)
  48. error_cls_name = type(e).__name__
  49. if error_cls_name in self.errors:
  50. custom_data = self.errors.get(error_cls_name, {})
  51. custom_data = custom_data.copy()
  52. status_code = custom_data.get('status', 500)
  53. if 'message' in custom_data:
  54. custom_data['message'] = custom_data['message'].format(
  55. message=str(e.description if hasattr(e, 'description') else e)
  56. )
  57. data.update(custom_data)
  58. # record the exception in the logs when we have a server error of status code: 500
  59. if status_code and status_code >= 500:
  60. exc_info = sys.exc_info()
  61. if exc_info[1] is None:
  62. exc_info = None
  63. current_app.log_exception(exc_info)
  64. if status_code == 406 and self.default_mediatype is None:
  65. # if we are handling NotAcceptable (406), make sure that
  66. # make_response uses a representation we support as the
  67. # default mediatype (so that make_response doesn't throw
  68. # another NotAcceptable error).
  69. supported_mediatypes = list(self.representations.keys()) # only supported application/json
  70. fallback_mediatype = supported_mediatypes[0] if supported_mediatypes else "text/plain"
  71. data = {
  72. 'code': 'not_acceptable',
  73. 'message': data.get('message')
  74. }
  75. resp = self.make_response(
  76. data,
  77. status_code,
  78. headers,
  79. fallback_mediatype = fallback_mediatype
  80. )
  81. elif status_code == 400:
  82. if isinstance(data.get('message'), dict):
  83. param_key, param_value = list(data.get('message').items())[0]
  84. data = {
  85. 'code': 'invalid_param',
  86. 'message': param_value,
  87. 'params': param_key
  88. }
  89. else:
  90. if 'code' not in data:
  91. data['code'] = 'unknown'
  92. resp = self.make_response(data, status_code, headers)
  93. else:
  94. if 'code' not in data:
  95. data['code'] = 'unknown'
  96. resp = self.make_response(data, status_code, headers)
  97. if status_code == 401:
  98. resp = self.unauthorized(resp)
  99. return resp