media_handler.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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 media services.
  14. """
  15. import json
  16. from baidubce import utils
  17. def dict_to_python_object(d):
  18. """
  19. dict to python object without converting camel key to a "pythonic" name
  20. :param d:
  21. :return:
  22. """
  23. attr = {}
  24. for k, v in utils.iteritems(d):
  25. if not isinstance(k, utils.compat.string_types):
  26. k = utils.compat.convert_to_string(k)
  27. attr[k] = v
  28. return utils.Expando(attr)
  29. def parse_json(http_response, response):
  30. """If the body is not empty, convert it to a python object and set as the value of
  31. response.body. http_response is always closed if no error occurs.
  32. :param http_response: the http_response object returned by HTTPConnection.getresponse()
  33. :type http_response: httplib.HTTPResponse
  34. :param response: general response object which will be returned to the caller
  35. :type response: baidubce.BceResponse
  36. :return: always true
  37. :rtype bool
  38. """
  39. body = http_response.read()
  40. if body:
  41. body = utils.compat.convert_to_string(body)
  42. response.__dict__.update(json.loads(body, object_hook=dict_to_python_object).__dict__)
  43. http_response.close()
  44. return True
  45. def parse_secret_key_response(http_response, response):
  46. """If the body is not empty, set body content as secretKey attribute of response
  47. :param http_response: the http_response object returned by HTTPConnection.getresponse()
  48. :type http_response: httplib.HTTPResponse
  49. :param response: general response object which will be returned to the caller
  50. :type response: baidubce.BceResponse
  51. :return: always true
  52. :rtype bool
  53. """
  54. body = http_response.read()
  55. if body:
  56. body = utils.compat.convert_to_string(body)
  57. response.encryption_key = body
  58. http_response.close()
  59. return True