http_utils.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. # -*- coding:UTF-8 -*-
  2. import requests
  3. import json
  4. import contants
  5. from print_log import printlog
  6. from urllib import parse
  7. def notify_cut_state(gcp_code, progress, msg):
  8. url = contants.get_notify_url()
  9. printlog(msg)
  10. data = {"gcp_code": gcp_code, "msg": msg, "progress": progress}
  11. content = http_request(url, data, False, 'get', False)
  12. printlog(str(content))
  13. def http_request(url, data, is_https=False, method='post', is_json_type=False):
  14. try:
  15. headers = dict()
  16. if is_json_type is True:
  17. content_type = 'application/json; charset=UTF-8'
  18. else:
  19. content_type = 'application/x-www-form-urlencoded; charset=UTF-8'
  20. if is_https is True:
  21. url = 'https://%s' % url
  22. else:
  23. url = 'http://%s' % url
  24. headers['Content-Type'] = content_type
  25. post_data = set_params(data) if is_json_type is False else json.dumps(data)
  26. if method == 'post':
  27. result = requests.post(url, data=post_data, headers=headers, verify=False)
  28. else:
  29. result = requests.get(url + '?' + post_data, headers=headers, verify=False)
  30. content = result.text
  31. if not content:
  32. return False
  33. return content
  34. except Exception as e:
  35. return False
  36. def set_params(params={}):
  37. """
  38. 生成参数
  39. """
  40. import urllib
  41. if not isinstance(params, dict):
  42. raise Exception("You must pass in a dictionary!")
  43. params_list = []
  44. for k, v in params.items():
  45. if isinstance(v, list) and v:
  46. if isinstance(v[0], dict):
  47. params_list.append((k, json.dumps(v)))
  48. else:
  49. params_list.extend([(k, x) for x in v])
  50. elif isinstance(v, dict):
  51. params_list.append((k, json.dumps(v)))
  52. else:
  53. params_list.append((k, v))
  54. return urllib.parse.urlencode(params_list)