You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

python_3x.py 1.4KB

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