我想使用asyncio在网络上流式传输大日志文件。我从数据库中检索数据,对其进行格式化,然后使用python的zlib对其进行压缩,然后通过网络进行流式处理。
这基本上是我使用的代码:
@asyncio.coroutine
def logs(requests):
# ...
yield from resp.prepare(request)
# gzip magic number and compression format
resp.write(b'\x1f\x8b\x08\x00\x00\x00\x00\x00')
compressor = compressobj()
for row in rows:
ip, uid, date, url, answer, volume = row
NCSA_ROW = '{} {} - [{}] "GET {} HTTP/1.0" {} {}\n'
row = NCSA_ROW.format(ip, uid, date, url, answer, volume)
row = row.encode('utf-8')
data = compressor.compress(row)
resp.write(data)
resp.write(compressor.flush())
return resp
我检索到的文件无法使用gunzip和zcat打开,出现以下错误:
gzip: out.gz: unexpected end of file
您的gzip标头是错误的(从8个字节而不是10个字节),然后跟随zlib流使用不同的标头和预告片。即使您有正确的gzip标头,并且如果您有原始的deflate流而不是gzip流,您仍然不会编写gzip预告片。
为此,请不要尝试编写自己的gzip标头。而是要求zlib编写一个完整的gzip流,该流将写入正确的标头,压缩数据和预告片。您可以通过提供to的wbits
值来做到这一点。31
compressobj()
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句