簡體   English   中英

Python解壓縮內存中的gzip數據而無需文件

[英]Python decompress gzip data in memory without file

我從HTTP回復中壓縮了數據。 我有以下代碼:

def gzipDecode(self, content):
    import StringIO
    import gzip

    outFilePath = 'test'

    compressedFile = StringIO.StringIO(content)
    decompressedFile = gzip.GzipFile(fileobj=compressedFile)
    with open(outFilePath, 'w') as outfile:
        outfile.write(decompressedFile.read())

    data = ''
    with open(outFilePath, 'r') as myfile:
        data=myfile.read().replace('\n', '')

    return data

解壓縮輸入的壓縮內容並返回字符串(http答復是json壓縮)。 - 有用。

但是我需要它而不創建測試文件-全部都在內存中。

我將其修改為:

def gzipDecode(self, content):
    import StringIO
    from io import BytesIO
    import gzip

    outFile = StringIO.StringIO()

    compressedFile = StringIO.StringIO(content)
    decompressedFile = gzip.GzipFile(fileobj=compressedFile)

    outFile.write(decompressedFile.read())
    outFile.flush()

    data = outFile.read().replace('\n', '')
    print "_" + data + "_"
    return data

但在解析json時崩潰( gzipDecode產生空輸出):

Traceback (most recent call last):
__
  File "/usr/lib/python2.7/SocketServer.py", line 593, in process_request_thread

    self.finish_request(request, client_address)
----------------------------------------
  File "/usr/lib/python2.7/SocketServer.py", line 334, in finish_request
Exception happened during processing of request from ('10.123.66.3', 39853)
    self.RequestHandlerClass(request, client_address, self)
----------------------------------------
  File "/usr/lib/python2.7/SocketServer.py", line 649, in __init__
    self.handle()
  File "/usr/lib/python2.7/BaseHTTPServer.py", line 340, in handle
    self.handle_one_request()
  File "/usr/lib/python2.7/BaseHTTPServer.py", line 328, in handle_one_request
    method()
  File "/tmp/test_server.py", line 92, in do_POST
    data = json.loads(file_content)
  File "/usr/lib/python2.7/json/__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python2.7/json/decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python2.7/json/decoder.py", line 384, in raw_decode
    raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded

我做什么不好?

您需要重新開始,然后才能閱讀:

outFile.write(decompressedFile.read())
outFile.flush()
outFile.seek(0)

data = outFile.read().replace('\n', '')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM