如何使用stringIO将base64数据压缩到缓冲区中?

时间:2019-03-27 04:40:44

标签: python python-2.7

在我的Python课程中应对这一挑战,似乎无法弄清楚如何继续。我认为到目前为止我是正确的,但任何输入都会令人惊讶。

目标:解码下面包含的base64 blob

import base64
import gzip
import StringIO

# This is our base64 encoded string
data = 'H4sIAAAAAAAAAL1X6W+j....'

def main():
    # Decode the base64 string into a variable
    decoded = base64.b64decode(data)
    # Create a variable that holds a stream living in a buffer

    # Decompress our stream

    # Print it to the screen

if __name__ == '__main__':
    main()

1 个答案:

答案 0 :(得分:0)

这是一个带有详细说明的解决方案

#Going by the comments in your code
#content of data variable is first gzip compressed and then base64 encoded
#In order to get the original content back, you must, 
#first base64 decode and then gzip uncompress it

#since gzip works on file objects, StringIO is to be used 
#StringIO module implements a file-like class, that reads and writes a string buffer 

import StringIO
import base64
import gzip

data = "...." #gzip compressed => base64 encoded
b64decoded = base64.b64decode(data) # base64 decode 
inputstream = StringIO.StringIO();
inputstream.write(b64decoded)
inputstream.seek(0)
#
uncompressGzip = gzip.GzipFile(fileobj=inputstream, mode='rb') # gzip uncompress
originalData = uncompressGzip.read()
print(originalData)

这是一个简单的测试,压缩=>编码=>解码=>取消压缩

import StringIO
import base64
import gzip

buf = StringIO.StringIO()
compressGzip = gzip.GzipFile(fileobj=buf, mode="wb")
compressGzip.write("Hello, how are you?")
compressGzip.close()
buf.seek(0)
data = base64.b64encode(buf.getvalue())
# your solution from this point onwards
b64decoded = base64.b64decode(data) # base64 decode 
inputstream = StringIO.StringIO();
inputstream.write(b64decoded)
inputstream.seek(0)
#
uncompressGzip = gzip.GzipFile(fileobj=inputstream, mode='rb') # gzip uncompress
originalData = uncompressGzip.read()
print(originalData)