Skip to content

Commit f8f6004

Browse files
committed
replace urlopen with non-global urllib2/urllib.request solution
1 parent 2c321b7 commit f8f6004

File tree

1 file changed

+8
-11
lines changed

1 file changed

+8
-11
lines changed

bagit.py

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@
1414
import signal
1515
import sys
1616
import tempfile
17-
import urllib
1817
import unicodedata
1918
import warnings
2019
from collections import defaultdict
@@ -27,10 +26,9 @@
2726
# pylint: disable=no-name-in-module, import-error, wrong-import-position
2827
if sys.version_info >= (3,):
2928
from urllib.parse import urlparse
30-
from urllib.request import urlopen, FancyURLopener
31-
import urllib.request
29+
from urllib.request import ProxyHandler, Request, build_opener
3230
else:
33-
from urllib import urlopen, FancyURLopener
31+
from urllib2 import ProxyHandler, Request, build_opener
3432
from urlparse import urlparse
3533

3634

@@ -591,16 +589,17 @@ def fetch_files_to_be_fetched(self):
591589
"""
592590
Fetches files from the fetch.txt
593591
"""
594-
if sys.version_info >= (3,):
595-
urllib.request._urlopener = BagFetcherURLOpener() # pylint: disable=protected-access
596-
else:
597-
urllib._urlopener = BagFetcherURLOpener() # pylint: disable=protected-access
592+
proxy_handler = ProxyHandler() # will default to adhere to *_proxy env vars
593+
opener = build_opener(proxy_handler)
594+
user_agent = "bagit.py/%s (Python/%s)" % (VERSION, sys.version_info)
598595
for url, expected_size, filename in self.fetch_entries():
599596
expected_size = int(expected_size) # FIXME should be int in the first place
600597
if filename in self.payload_files():
601598
LOGGER.info(_("File already fetched: %s"), filename)
602599
continue
603-
resp = urlopen(url)
600+
req = Request(url)
601+
req.add_header('User-Agent', user_agent)
602+
resp = opener.open(req)
604603
headers = resp.info()
605604
if "content-length" not in headers:
606605
LOGGER.warning(_("Server sent no content-length for <%s>"), url)
@@ -977,8 +976,6 @@ def _path_is_dangerous(self, path):
977976
common = os.path.commonprefix((bag_path, real_path))
978977
return not (common == bag_path)
979978

980-
class BagFetcherURLOpener(FancyURLopener):
981-
version = "bagit.py/%s (Python/%s)" % (VERSION, sys.version_info)
982979

983980
class BagError(Exception):
984981
pass

0 commit comments

Comments
 (0)