Ensure URLs are closed with a context manager.

This commit is contained in:
Elliott Sales de Andrade 2016-08-24 21:39:05 -04:00
parent fe0aa7daff
commit 181d9a891d
1 changed files with 21 additions and 20 deletions

View File

@ -13,6 +13,7 @@
# limitations under the License. # limitations under the License.
from .. import mlog from .. import mlog
import contextlib
import urllib.request, os, hashlib, shutil import urllib.request, os, hashlib, shutil
import subprocess import subprocess
import sys import sys
@ -137,26 +138,26 @@ class Resolver:
resp = open_wrapdburl(url) resp = open_wrapdburl(url)
else: else:
resp = urllib.request.urlopen(url) resp = urllib.request.urlopen(url)
dlsize = int(resp.info()['Content-Length']) with contextlib.closing(resp) as resp:
print('Download size:', dlsize) dlsize = int(resp.info()['Content-Length'])
print('Downloading: ', end='') print('Download size:', dlsize)
sys.stdout.flush() print('Downloading: ', end='')
printed_dots = 0 sys.stdout.flush()
blocks = [] printed_dots = 0
downloaded = 0 blocks = []
while True: downloaded = 0
block = resp.read(blocksize) while True:
if block == b'': block = resp.read(blocksize)
break if block == b'':
downloaded += len(block) break
blocks.append(block) downloaded += len(block)
ratio = int(downloaded/dlsize * 10) blocks.append(block)
while printed_dots < ratio: ratio = int(downloaded/dlsize * 10)
print('.', end='') while printed_dots < ratio:
sys.stdout.flush() print('.', end='')
printed_dots += 1 sys.stdout.flush()
print('') printed_dots += 1
resp.close() print('')
return b''.join(blocks) return b''.join(blocks)
def get_hash(self, data): def get_hash(self, data):