python_3x.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import logging
  2. import os
  3. import ssl
  4. import urllib.request
  5. from urllib import parse
  6. from urllib.error import HTTPError
  7. # Create an SSL context that allows for a lower level of security
  8. ssl_context = ssl.create_default_context()
  9. ssl_context.set_ciphers("HIGH:!DH:!aNULL")
  10. ssl_context.check_hostname = False
  11. ssl_context.verify_mode = ssl.CERT_NONE
  12. # Create an opener object and pass in a custom SSL context
  13. opener = urllib.request.build_opener(urllib.request.HTTPSHandler(context=ssl_context))
  14. urllib.request.install_opener(opener)
  15. logger = logging.getLogger(__name__)
  16. def http_request(url, timeout, headers={}):
  17. try:
  18. request = urllib.request.Request(url, headers=headers)
  19. res = urllib.request.urlopen(request, timeout=timeout)
  20. body = res.read().decode("utf-8")
  21. return res.code, body
  22. except HTTPError as e:
  23. if e.code == 304:
  24. logger.warning("http_request error,code is 304, maybe you should check secret")
  25. return 304, None
  26. logger.warning("http_request error,code is %d, msg is %s", e.code, e.msg)
  27. raise e
  28. def url_encode(params):
  29. return parse.urlencode(params)
  30. def makedirs_wrapper(path):
  31. os.makedirs(path, exist_ok=True)