<s> from gzip import GzipFile <EOL> from StringIO import StringIO <EOL> from . core import Middleware <EOL> def compress ( data , level = <NUM_LIT:6> ) : <EOL> out = StringIO ( ) <EOL> f = GzipFile ( fileobj = out , mode = '<STR_LIT:wb>' , compresslevel = level ) <EOL> f . write ( data ) <EOL> f . close ( ) <EOL> return out . getvalue ( ) <EOL> class GzipMiddleware ( Middleware ) : <EOL> def __init__ ( self , compress_level = <NUM_LIT:6> ) : <EOL> self . compress_level = compress_level <EOL> def request ( self , next , request ) : <EOL> resp = next ( ) <EOL> resp . vary . add ( '<STR_LIT>' ) <EOL> if resp . content_encoding or not request . accept_encodings [ '<STR_LIT>' ] : <EOL> return resp <EOL> if '<STR_LIT>' in request . user_agent . browser : <EOL> if not ( resp . content_type . startswith ( '<STR_LIT>' ) or <EOL> '<STR_LIT>' in resp . content_type ) : <EOL> return resp <EOL> if resp . is_streamed : <EOL> return resp <EOL> else : <EOL> comp_content = compress ( resp . data , self . compress_level ) <EOL> if len ( comp_content ) >= len ( resp . data ) : <EOL> return resp <EOL> resp . response = [ comp_content ] <EOL> resp . content_length = len ( comp_content ) <EOL> resp . content_encoding = '<STR_LIT>' <EOL> return resp </s>
