4
4
"""Utilities for conversion between urls and file paths"""
5
5
6
6
import os
7
+ import sys
7
8
8
9
from urllib import (
9
10
parse as urlparse ,
@@ -44,16 +45,20 @@ def filepath_from_url(urlstr):
44
45
Take an url and return a filepath.
45
46
46
47
URLs can either be encoded according to the `RFC 3986`_ standard or not.
47
- Additionally, Windows mapped paths need to be accounted for when processing a
48
- URL; however, there are `ongoing discussions`_ about how to best handle this within
49
- Python. This function is meant to cover all of these scenarios in the interim.
48
+ Additionally, Windows mapped drive letter and UNC paths need to be accounted for
49
+ when processing URL(s); however, there are `ongoing discussions`_ about how to best
50
+ handle this within Python developer community. This function is meant to cover
51
+ these scenarios in the interim.
50
52
51
53
.. _RFC 3986: https://tools.ietf.org/html/rfc3986#section-2.1
52
54
.. _ongoing discussions: https://discuss.python.org/t/file-uris-in-python/15600
53
55
"""
54
56
57
+ # De-encode the URL
58
+ decoded_url_str = urlparse .unquote (urlstr )
59
+
55
60
# Parse provided URL
56
- parsed_result = urlparse .urlparse (urlstr )
61
+ parsed_result = urlparse .urlparse (decoded_url_str )
57
62
58
63
# Convert the parsed URL to a path
59
64
filepath = Path (request .url2pathname (parsed_result .path ))
@@ -62,10 +67,18 @@ def filepath_from_url(urlstr):
62
67
if PureWindowsPath (parsed_result .netloc ).drive :
63
68
filepath = Path (parsed_result .netloc + parsed_result .path )
64
69
65
- # Otherwise check if the specified index is a windows drive, then offset the path
70
+ # Check if the specified index is a windows drive, if it is then do nothing
71
+ elif PureWindowsPath (filepath .parts [0 ]).drive :
72
+ filepath = filepath
73
+
74
+ # Check if the specified index is a windows drive, then offset the path
66
75
elif PureWindowsPath (filepath .parts [1 ]).drive :
67
76
# Remove leading "/" if/when `request.url2pathname` yields "/S:/path/file.ext"
68
77
filepath = filepath .relative_to (filepath .root )
69
78
79
+ # Last resort, if using a "file" schema, then strip the "file:" prefix
80
+ elif parsed_result .scheme == 'file' :
81
+ filepath = Path (decoded_url_str .strip ('file:' ))
82
+
70
83
# Convert "\" to "/" if needed
71
84
return filepath .as_posix ()
0 commit comments