urls.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import os
  2. import sys
  3. import urllib.parse
  4. import urllib.request
  5. from typing import Optional
  6. def get_url_scheme(url):
  7. # type: (str) -> Optional[str]
  8. if ":" not in url:
  9. return None
  10. return url.split(":", 1)[0].lower()
  11. def path_to_url(path):
  12. # type: (str) -> str
  13. """
  14. Convert a path to a file: URL. The path will be made absolute and have
  15. quoted path parts.
  16. """
  17. path = os.path.normpath(os.path.abspath(path))
  18. url = urllib.parse.urljoin("file:", urllib.request.pathname2url(path))
  19. return url
  20. def url_to_path(url):
  21. # type: (str) -> str
  22. """
  23. Convert a file: URL to a path.
  24. """
  25. assert url.startswith(
  26. "file:"
  27. ), f"You can only turn file: urls into filenames (not {url!r})"
  28. _, netloc, path, _, _ = urllib.parse.urlsplit(url)
  29. if not netloc or netloc == "localhost":
  30. # According to RFC 8089, same as empty authority.
  31. netloc = ""
  32. elif sys.platform == "win32":
  33. # If we have a UNC path, prepend UNC share notation.
  34. netloc = "\\\\" + netloc
  35. else:
  36. raise ValueError(
  37. f"non-local file URIs are not supported on this platform: {url!r}"
  38. )
  39. path = urllib.request.url2pathname(netloc + path)
  40. return path