Skip to content

Commit

Permalink
Merge pull request closeio#7 from nicorevin/master
Browse files Browse the repository at this point in the history
Use with statement for GzipFile and werkzeug to calculate response length
  • Loading branch information
William Fagan committed Jul 18, 2014
2 parents d57a9af + d644440 commit ce84fd7
Showing 1 changed file with 7 additions and 7 deletions.
14 changes: 7 additions & 7 deletions flask_compress.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import gzip
from gzip import GzipFile
try:
from io import BytesIO as IO
except:
Expand Down Expand Up @@ -67,22 +67,22 @@ def after_request(self, response):

if (response.status_code < 200 or
response.status_code >= 300 or
len(response.data) < app.config['COMPRESS_MIN_SIZE'] or
response.content_length < app.config['COMPRESS_MIN_SIZE'] or
'Content-Encoding' in response.headers):
return response

level = app.config['COMPRESS_LEVEL']

gzip_buffer = IO()
gzip_file = gzip.GzipFile(mode='wb', compresslevel=level,
fileobj=gzip_buffer)
gzip_file.write(response.data)
gzip_file.close()
with GzipFile(mode='wb',
compresslevel=level,
fileobj=gzip_buffer) as gzip_file:
gzip_file.write(response.data)

response.data = gzip_buffer.getvalue()

response.headers['Content-Encoding'] = 'gzip'
response.headers['Content-Length'] = len(response.data)
response.headers['Content-Length'] = response.content_length

vary = response.headers.get('Vary')
if vary:
Expand Down

0 comments on commit ce84fd7

Please sign in to comment.