python下实现php的gzinflate,gzdeflate
#!/usr/bin/env python
# coding: utf-8
import zlib
import base64
def gzinflate(base64_string):
compressed_data = base64.b64decode(base64_string)
return zlib.decompress(compressed_data, -15)
OR (python 3):
#input is raw compressed data
def gzinflate(compressed: bytes) -> bytes:
return zlib.decompress(compressed, -zlib.MAX_WBITS)
gzdeflate
#!/usr/bin/env python
# coding: utf-8
import zlib
import base64
def gzdeflate(string):
compressed_data = zlib.compress(string)[2:-4]
return base64.b64encode(compressed_data)
OR a bit longer but much correct way at same time (python 3):
import zlib
# bytes('some string', encoding='utf-8') to convert string to bytes (an encoding may differs)
def gzdeflate(data: bytes) -> bytes:
compressor = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS)
compressed = compressor.compress(data)
compressed += compressor.flush()
return compressed
#output is raw compressed data, you can encode it to base64 by
#base64.b64encode(compresed)