Gzip responses.
This commit is contained in:
		
							parent
							
								
									b0dcc6d3c6
								
							
						
					
					
						commit
						f640268793
					
				
					 1 changed files with 33 additions and 0 deletions
				
			
		|  | @ -1,4 +1,6 @@ | ||||||
| import flask; from flask import request | import flask; from flask import request | ||||||
|  | import gzip | ||||||
|  | import io | ||||||
| import mimetypes | import mimetypes | ||||||
| import traceback | import traceback | ||||||
| 
 | 
 | ||||||
|  | @ -43,6 +45,37 @@ file_cache_manager = caching.FileCacheManager( | ||||||
|     max_age=BROWSER_CACHE_DURATION, |     max_age=BROWSER_CACHE_DURATION, | ||||||
| ) | ) | ||||||
| 
 | 
 | ||||||
|  | gzip_minimum_size = 500 | ||||||
|  | gzip_level = 3 | ||||||
|  | @site.after_request | ||||||
|  | def after_request(response): | ||||||
|  |     ''' | ||||||
|  |     Thank you close.io. | ||||||
|  |     https://github.com/closeio/Flask-gzip | ||||||
|  |     ''' | ||||||
|  |     accept_encoding = request.headers.get('Accept-Encoding', '') | ||||||
|  | 
 | ||||||
|  |     bail = False | ||||||
|  |     bail = bail or response.status_code < 200 | ||||||
|  |     bail = bail or response.status_code >= 300 | ||||||
|  |     bail = bail or response.direct_passthrough | ||||||
|  |     bail = bail or len(response.get_data()) < gzip_minimum_size | ||||||
|  |     bail = bail or 'gzip' not in accept_encoding.lower() | ||||||
|  |     bail = bail or 'Content-Encoding' in response.headers | ||||||
|  | 
 | ||||||
|  |     if bail: | ||||||
|  |         return response | ||||||
|  | 
 | ||||||
|  |     gzip_buffer = io.BytesIO() | ||||||
|  |     gzip_file = gzip.GzipFile(mode='wb', compresslevel=gzip_level, fileobj=gzip_buffer) | ||||||
|  |     gzip_file.write(response.get_data()) | ||||||
|  |     gzip_file.close() | ||||||
|  |     response.set_data(gzip_buffer.getvalue()) | ||||||
|  |     response.headers['Content-Encoding'] = 'gzip' | ||||||
|  |     response.headers['Content-Length'] = len(response.get_data()) | ||||||
|  | 
 | ||||||
|  |     return response | ||||||
|  | 
 | ||||||
| def P_wrapper(function): | def P_wrapper(function): | ||||||
|     def P_wrapped(thingid, response_type): |     def P_wrapped(thingid, response_type): | ||||||
|         if response_type not in {'html', 'json'}: |         if response_type not in {'html', 'json'}: | ||||||
|  |  | ||||||
		Loading…
	
		Reference in a new issue