需求
接口输出到前端信息,随着量增大,传输数据变大,响应时间增加,影响用户体验
解决方案
分页请求或传输文件压缩gzip
情况对比
不压缩
1 2 3
| return { 'books': marshal(book_list, fav_book_fields), }
|

gzip 压缩之后
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| from flask import make_response, request, jsonify import StringIO import gzip
re_dict = { 'books': marshal(book_list, fav_book_fields), } response = make_response(jsonify(**re_dict), 200)
gzip_buffer = StringIO.StringIO()#声明一个内存文件 gzip_file = gzip.GzipFile(mode='wb', compresslevel=6, fileobj=gzip_buffer)#声明一个压缩对象 gzip_file.write(response.data)#将response的data通过压缩对象写入到缓存区中 gzip_file.close() response.data = gzip_buffer.getvalue()#从缓存区获取压缩后的文件 response.headers['Content-Encoding'] = 'gzip' response.headers['Content-Length'] = len(response.data)
return response
|

节省三分之二时间,也可以根据需求相应调整compresslevel
小结
给flask项目中所有api添加压缩,在蓝图中api init after_request 中统一添加
第三方插件flask-compress