util.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import os
  2. import errno
  3. from pathlib import Path
  4. import requests
  5. import sys
  6. PY3 = sys.version_info[0] >= 3
  7. if PY3:
  8. text_types = (str,)
  9. else:
  10. text_types = (str, unicode) # analysis:ignore
  11. def download(url, target):
  12. """Download a file using requests.
  13. This is like urllib.request.urlretrieve, but requests validates SSL
  14. certificates by default.
  15. """
  16. if isinstance(target, Path):
  17. target = str(target)
  18. r = requests.get(url, stream=True)
  19. r.raise_for_status()
  20. with open(target, 'wb') as f:
  21. for chunk in r.iter_content(chunk_size=1024):
  22. if chunk:
  23. f.write(chunk)
  24. def get_cache_dir(ensure_existence=False):
  25. if os.name == 'posix' and sys.platform != 'darwin':
  26. # Linux, Unix, AIX, etc.
  27. # use ~/.cache if empty OR not set
  28. xdg = os.environ.get("XDG_CACHE_HOME", None) or (os.path.expanduser('~/.cache'))
  29. p = Path(xdg, 'pynsist')
  30. elif sys.platform == 'darwin':
  31. p = Path(os.path.expanduser('~'), 'Library/Caches/pynsist')
  32. else:
  33. # Windows (hopefully)
  34. local = os.environ.get('LOCALAPPDATA', None) or (os.path.expanduser('~\\AppData\\Local'))
  35. p = Path(local, 'pynsist')
  36. if ensure_existence:
  37. try:
  38. p.mkdir(parents=True)
  39. except OSError as e:
  40. # Py2 compatible equivalent of FileExistsError
  41. if e.errno != errno.EEXIST:
  42. raise
  43. return p