[docs]classGZipMiddleware(MiddlewareMixin):""" Compress content if the browser allows gzip compression. Set the Vary header accordingly, so that caches will base their storage on the Accept-Encoding header. """defprocess_response(self,request,response):# It's not worth attempting to compress really short responses.ifnotresponse.streamingandlen(response.content)<200:returnresponse# Avoid gzipping if we've already got a content-encoding.ifresponse.has_header('Content-Encoding'):returnresponsepatch_vary_headers(response,('Accept-Encoding',))ae=request.META.get('HTTP_ACCEPT_ENCODING','')ifnotre_accepts_gzip.search(ae):returnresponseifresponse.streaming:# Delete the `Content-Length` header for streaming content, because# we won't know the compressed size until we stream it.response.streaming_content=compress_sequence(response.streaming_content)delresponse['Content-Length']else:# Return the compressed content only if it's actually shorter.compressed_content=compress_string(response.content)iflen(compressed_content)>=len(response.content):returnresponseresponse.content=compressed_contentresponse['Content-Length']=str(len(response.content))# If there is a strong ETag, make it weak to fulfill the requirements# of RFC 7232 section-2.1 while also allowing conditional request# matches on ETags.etag=response.get('ETag')ifetagandetag.startswith('"'):response['ETag']='W/'+etagresponse['Content-Encoding']='gzip'returnresponse