Fixed #27020 -- Used a context manager to close files.

This commit is contained in:
Ville Skyttä 2016-08-05 02:45:14 +03:00 committed by Tim Graham
parent 50e299dbfb
commit a2fb2b3a1f
5 changed files with 21 additions and 21 deletions

View File

@ -324,10 +324,15 @@ class TemplateDetailView(BaseAdminDocsView):
# This doesn't account for template loaders (#24128).
for index, directory in enumerate(default_engine.dirs):
template_file = os.path.join(directory, template)
if os.path.exists(template_file):
with open(template_file) as f:
template_contents = f.read()
else:
template_contents = ''
templates.append({
'file': template_file,
'exists': os.path.exists(template_file),
'contents': lambda: open(template_file).read() if os.path.exists(template_file) else '',
'contents': template_contents,
'order': index,
})
kwargs.update({

View File

@ -169,7 +169,8 @@ class CommonPasswordValidator(object):
def __init__(self, password_list_path=DEFAULT_PASSWORD_LIST_PATH):
try:
common_passwords_lines = gzip.open(password_list_path).read().decode('utf-8').splitlines()
with gzip.open(password_list_path) as f:
common_passwords_lines = f.read().decode('utf-8').splitlines()
except IOError:
with open(password_list_path) as f:
common_passwords_lines = f.readlines()

View File

@ -15,9 +15,8 @@ except ImportError:
def compress_kml(kml):
"Returns compressed KMZ from the given KML string."
kmz = BytesIO()
zf = zipfile.ZipFile(kmz, 'a', zipfile.ZIP_DEFLATED)
zf.writestr('doc.kml', kml.encode(settings.DEFAULT_CHARSET))
zf.close()
with zipfile.ZipFile(kmz, 'a', zipfile.ZIP_DEFLATED) as zf:
zf.writestr('doc.kml', kml.encode(settings.DEFAULT_CHARSET))
kmz.seek(0)
return kmz.read()

View File

@ -291,9 +291,8 @@ def phone2numeric(phone):
# Used with permission.
def compress_string(s):
zbuf = BytesIO()
zfile = GzipFile(mode='wb', compresslevel=6, fileobj=zbuf)
zfile.write(s)
zfile.close()
with GzipFile(mode='wb', compresslevel=6, fileobj=zbuf) as zfile:
zfile.write(s)
return zbuf.getvalue()
@ -321,15 +320,14 @@ class StreamingBuffer(object):
# Like compress_string, but for iterators of strings.
def compress_sequence(sequence):
buf = StreamingBuffer()
zfile = GzipFile(mode='wb', compresslevel=6, fileobj=buf)
# Output headers...
yield buf.read()
for item in sequence:
zfile.write(item)
data = buf.read()
if data:
yield data
zfile.close()
with GzipFile(mode='wb', compresslevel=6, fileobj=buf) as zfile:
# Output headers...
yield buf.read()
for item in sequence:
zfile.write(item)
data = buf.read()
if data:
yield data
yield buf.read()

View File

@ -11,11 +11,8 @@ from django.test.client import conditional_content_removal
# based on Python 3.3's gzip.compress
def gzip_compress(data):
buf = io.BytesIO()
f = gzip.GzipFile(fileobj=buf, mode='wb', compresslevel=0)
try:
with gzip.GzipFile(fileobj=buf, mode='wb', compresslevel=0) as f:
f.write(data)
finally:
f.close()
return buf.getvalue()