_http.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import requests
  17. def post(url, req_body, headers=None, verify_peer=False):
  18. """ post http request to slb service
  19. :param url: url path
  20. :param req_body: http request body
  21. :param headers: http headers
  22. :param verify_peer: (optional) Either a boolean, in which case it controls whether we verify
  23. the server's TLS certificate, or a string, in which case it must be a path
  24. to a CA bundle to use. Defaults to ``True``.
  25. :return:
  26. success return response
  27. fali return None
  28. """
  29. try:
  30. response = requests.post(url, data=req_body, headers=headers, timeout=10, verify=verify_peer)
  31. return response
  32. except Exception as e:
  33. raise ValueError('caught exception when post {0}. {1}'.format(url, e))
  34. def _format_http_text(method, url, headers, body):
  35. """
  36. print http head and body for request or response
  37. For examples: _format_http_text('', title, response.headers, response.text)
  38. """
  39. result = method + ' ' + url + '\n'
  40. if headers is not None:
  41. for key, value in headers.items():
  42. result = result + key + ': ' + value + '\n'
  43. result = result + body
  44. return result