简体   繁体   English

python - 如何膨胀 gzipped,base64d 字符串

[英]python - how to inflate gzipped, base64d string

I'm just wondering how is it possible to inflate/decompress a string of text that is a gzipped compressed string that also hase base64 encoding?我只是想知道如何膨胀/解压缩文本字符串,该文本字符串是 gzipped 压缩字符串,也有 base64 编码?

For instance, all the python examples seem to focus on opening a file, whereas I want to work on a gzipped string.例如,所有 python 示例似乎都专注于打开文件,而我想处理 gzipped 字符串。

Under python3, other answers didn't help me but I found this: 在python3下,其他答案对我没有帮助,但我发现了这个:

import base64
import zlib
data = 'H4sIAAAAAAAAAHWPwQqCQBCGX0Xm7EFtK+smZBEUgXoLCdMhFtKV3akI8d0bLYmibvPPN3wz00CJxmQnTO41whwWQRIctmEcB6sQbFC3CjW3XW8kxpOpP+OC22d1Wml1qZkQGtoMsScxaczKN3plG8zlaHIta5KqWsozoTYw3/djzwhpLwivWFGHGpAFe7DL68JlBUk+l7KSN7tCOEJ4M3/qOI49vMHj+zCKdlFqLaU2ZHV2a4Ct/an0/ivdX8oYc1UVX860fQDQiMdxRQEAAA=='

json_str = zlib.decompress(base64.b64decode(data), 16 + zlib.MAX_WBITS).decode('utf-8')

hope this helps 希望这可以帮助

For me the following code worked best (gzip without file)对我来说,以下代码效果最好(无文件的 gzip)

import base64
import gzip

base64_message = # string containing base64 encoded data
base64_bytes = base64_message.encode('utf-8')
message_bytes = base64.b64decode(base64_bytes)
print(gzip.decompress(message_bytes))

You can use base64 and zlib libraries: 您可以使用base64和zlib库:

import base64, zlib
decoded_data = zlib.decompress(base64.b64decode(encoded_data))

The gzip module is only for file operations: https://docs.python.org/2/library/gzip.html . gzip模块仅用于文件操作: https//docs.python.org/2/library/gzip.html It uses zlib for actual compression/decompression. 它使用zlib进行实际压缩/解压缩。

The GzipFile in the gzip module allows you to provide a fileobj argument. gzip模块中的GzipFile允许您提供fileobj参数。 If the string is really gzipped (ie: it has the proper headers) you can then wrap the string in a StringIO object and pass it around 如果字符串确实是gzip (即:它有正确的标题),那么你可以将字符串包装在StringIO对象中并传递它

import base64
import gzip
from io import StringIO

gzippedstr = fetchgzippedstr()  # wherever it may come from
gzcontent = gzip.GzipFile(fileobj=StringIO(gzippedstr))
b64content = gzcontent.read()
content = base64.b64decode(b64content)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM