bls_handler.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. # Copyright 2014 Baidu, Inc.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
  4. # except in compliance with the License. You may obtain a copy of the License at
  5. #
  6. # http://www.apache.org/licenses/LICENSE-2.0
  7. #
  8. # Unless required by applicable law or agreed to in writing, software distributed under the
  9. # License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
  10. # either express or implied. See the License for the specific language governing permissions
  11. # and limitations under the License.
  12. """
  13. This module provides general http handler functions for processing http responses from BCM services.
  14. """
  15. import http.client
  16. import json
  17. from baidubce import compat, utils
  18. from baidubce.exception import BceClientError
  19. from baidubce.exception import BceServerError
  20. def parse_error(http_response, response):
  21. """If the body is not empty, convert it to a python object and set as the value of
  22. response.body. http_response is always closed if no error occurs.
  23. :param http_response: the http_response object returned by HTTPConnection.getresponse()
  24. :type http_response: httplib.HTTPResponse
  25. :param response: general response object which will be returned to the caller
  26. :type response: baidubce.BceResponse
  27. :return: false if http status code is 2xx, raise an error otherwise
  28. :rtype bool
  29. :raise baidubce.exception.BceClientError: if http status code is NOT 2xx
  30. """
  31. if http_response.status // 100 == http.client.OK // 100:
  32. return False
  33. if http_response.status // 100 == http.client.CONTINUE // 100:
  34. raise BceClientError(b'Can not handle 1xx http status code')
  35. body = http_response.read()
  36. if not body:
  37. bse = BceServerError(http_response.reason, request_id=response.metadata.bce_request_id)
  38. bse.status_code = http_response.status
  39. raise bse
  40. error_dict = json.loads(compat.convert_to_string(body))
  41. message = str(error_dict)
  42. if 'message' in error_dict and error_dict['message'] is not None:
  43. message = error_dict['message']
  44. code = "Exception"
  45. if 'code' in error_dict and error_dict['code'] is not None:
  46. code = error_dict['code']
  47. request_id = response.metadata.bce_request_id
  48. if 'request_id' in error_dict and error_dict['request_id'] is not None:
  49. request_id = error_dict['request_id']
  50. bse = BceServerError(message, code=code, request_id=request_id)
  51. bse.status_code = http_response.status
  52. raise bse