Last active
December 25, 2015 13:09
-
-
Save zlalanne/6981712 to your computer and use it in GitHub Desktop.
Download a file using urllib2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def dl_file(url, directory=os.path.dirname(__file__), user=None, password=None, filename=None): | |
""" | |
Download a file from a url to a directory | |
@param url: url of a file | |
@param directory: directory to save the file into | |
@return: True if file was downloaded successfully, False otherwise | |
""" | |
# Disable the proxy | |
proxy_handler = urllib2.ProxyHandler({}) | |
opener = urllib2.build_opener(proxy_handler) | |
urllib2.install_opener(opener) | |
request = urllib2.Request(url) | |
# Encode username and password if exists | |
if user and password: | |
base64string = base64.encodestring("{}:{}".format(user, password)).replace("\n", "") | |
request.add_header("Authorization", "Basic {}".format(base64string)) | |
if not filename: | |
filename = os.path.basename(url) | |
# Open the url | |
try: | |
result = urllib2.urlopen(request) | |
logging.info("Downloading {}".format(url)) | |
# Open our local file for writing | |
with open(os.path.join(directory, filename), "wb") as local_file: | |
local_file.write(result.read()) | |
# Handle errors | |
except urllib2.HTTPError, e: | |
logging.error("HTTP Error: {} {}".format(e.code, url)) | |
return False | |
except urllib2.URLError, e: | |
logging.error("URL Error: {} {}".format(e.reason, url)) | |
return False | |
else: | |
return True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment