沈阳华威天下培训部总结HTTP 协议中你必须知道的三种数据格式(4)
Python 中的 zlib 库
在python中有zlib库它可以解决gzip、deflate和zlib压缩。这三种对应的压缩方式分别是:
RFC 1950 (zlib compressed format)
RFC 1951 (deflate compressed format)
RFC 1952 (gzip compressed format)
虽说是 Python 库但是底层还是 C(C++) 来实现的,这个 http-parser 也是 C 实现的源码Nodejs 的 http-parser 也是 C 实现的源码,zlib 的 C 源码在这里()。C 真的好牛逼呀!
在解压缩的过程中需要选择 windowBits 参数:
to (de-)compress deflate format, use wbits = -zlib.MAX_WBITS
to (de-)compress zlib format, use wbits = zlib.MAX_WBITS
to (de-)compress gzip format, use wbits = zli
例如,解压gzip数据就可以使用ress(data, _WBITS | 16),解压deflate数据可以使用ress(data,- _WBITS)。
当然对于gzip文件也可以使用python的gzip包来解决,可以参考下面的代码:
>>> import gzip
>>> import StringIO
>>> fio = StringIO.StringIO(gzip_data)
>>> f = gzip.GzipFile(fileobj=fio)
>>> f.read()
39;test39;
>>> f.close()
也可以在解压的时候自动加入头检测把32加入头中就可以触发头检测,例如:
>>> zlib.decompress(gzip_data, zlib.MAX_WBITS|32)
39;test39;
>>> zlib.decompress(zlib_data, zlib.MAX_WBITS|32)
39;test39;
以上参考 stackoverflow How can I decompress a gzip stream with zlib。
刚接触这些东西的时候每天都会稀奇古怪的报一些错误,基本上 Google 一下都能解决。