我正在尝试使用wsgi输出gzip编码的字符串,这是我的尝试,但是不幸的是,浏览器仅解码第一个字符串,有帮助吗?
测试1:
import zlib
def application(environ, start_response):
headers = [('Content-Type', 'text/html; charset=utf-8'),('Content-Encoding', 'gzip')]
data = b'\x1f\x8b\x08\x00\x00\x00\x00\x00'
data += zlib.compress(b'test')[:-4]
data += zlib.compress(b'test2')[:-4]
headers.append(('Content-Length', str(len(data))))
start_response('200 OK',headers)
return [data]
测试2:
import zlib
def application(environ, start_response):
headers = [('Content-Type', 'text/html; charset=utf-8'),('Content-Encoding', 'gzip')]
data = b'\x1f\x8b\x08\x00\x00\x00\x00\x00'
data += zlib.compress(b'test')
data += zlib.compress(b'test2')
headers.append(('Content-Length', str(len(data))))
start_response('200 OK',headers)
return [data]
测试3:
import zlib
def application(environ, start_response):
headers = [('Content-Type', 'text/html; charset=utf-8'),('Content-Encoding', 'gzip')]
start_response('200 OK',headers)
yield b'\x1f\x8b\x08\x00\x00\x00\x00\x00'
yield zlib.compress(b'test')[:-4]
yield zlib.compress(b'test2')[:-4]
测试4:
import zlib
def application(environ, start_response):
headers = [('Content-Type', 'text/html; charset=utf-8'),('Content-Encoding', 'gzip')]
start_response('200 OK',headers)
yield b'\x1f\x8b\x08\x00\x00\x00\x00\x00'
yield zlib.compress(b'test')
yield zlib.compress(b'test2')
测试5:
import gzip
def application(environ, start_response):
headers = [('Content-Type', 'text/html; charset=utf-8'),('Content-Encoding', 'gzip')]
start_response('200 OK',headers)
yield gzip.compress(b'test')
yield gzip.compress(b'test2')
我认为问题在于:
gzip.compress(b'test')
返回一个字符串
header content THE END
在里面。
这意味着当您阅读它时,解压缩将仅返回b'test'。自己尝试。
两种解决方案取决于您要实现的目标:
compress
做这个:
def compress(data, compresslevel=9):
"""Compress data in one shot and return the compressed string.
Optional argument is the compression level, in range of 0-9.
"""
buf = io.BytesIO()
with GzipFile(fileobj=buf, mode='wb', compresslevel=compresslevel) as f:
f.write(data)
return buf.getvalue()
做这样的事情:
import gzip, io
def application(environ, start_response):
headers = [('Content-Type', 'text/html; charset=utf-8'),('Content-Encoding', 'gzip')]
start_response('200 OK',headers)
buf = io.BytesIO()
with GzipFile(fileobj=buf, mode='wb') as f:
f.write(b'test')
f.write(b'test2')
return buf
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句