util.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. from . import __version__
  19. headers = {'user-agent': 'Pynsist/'+__version__}
  20. r = requests.get(url, headers=headers, stream=True)
  21. r.raise_for_status()
  22. with open(target, 'wb') as f:
  23. for chunk in r.iter_content(chunk_size=1024):
  24. if chunk:
  25. f.write(chunk)
  26. def get_cache_dir(ensure_existence=False):
  27. if os.name == 'posix' and sys.platform != 'darwin':
  28. # Linux, Unix, AIX, etc.
  29. # use ~/.cache if empty OR not set
  30. xdg = os.environ.get("XDG_CACHE_HOME", None) or (os.path.expanduser('~/.cache'))
  31. p = Path(xdg, 'pynsist')
  32. elif sys.platform == 'darwin':
  33. p = Path(os.path.expanduser('~'), 'Library/Caches/pynsist')
  34. else:
  35. # Windows (hopefully)
  36. local = os.environ.get('LOCALAPPDATA', None) or (os.path.expanduser('~\\AppData\\Local'))
  37. p = Path(local, 'pynsist')
  38. if ensure_existence:
  39. try:
  40. p.mkdir(parents=True)
  41. except OSError as e:
  42. # Py2 compatible equivalent of FileExistsError
  43. if e.errno != errno.EEXIST:
  44. raise
  45. return p