Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def scheme_from_uri(uri):
"""Return a scheme from a parsed uri."""
# Handle case where path does not contain a scheme
# i.e. '/abspath/foo' or 'relpath/foo'
# Do not test `if parts.scheme` because of how urlparse handles Windows
# file paths -- i.e. 'C:\\foo' => scheme = 'c' :(
return uri.scheme if '://' in urllib.parse.urlunparse(uri) else 'file'
def uri_from_filepath(filepath):
"""Return a URI compatible with urllib, handling URIs and file paths."""
parts = urllib.parse.urlparse(filepath)
scheme = scheme_from_uri(parts)
if scheme != 'file':
# Return non-file paths unchanged
return filepath
# Expand relative file paths and convert them to uri-style
path = urllib.request.pathname2url(os.path.abspath(os.path.expanduser(
''.join([x for x in [parts.netloc, parts.path] if x]))))
return urllib.parse.urlunparse((scheme, '', path, '', '', ''))