Search code examples
pythonpython-2.7gzipencode

How to compress the string using gzip and encode in python 2.7


I'm trying to compress and encode my string using gGIP in python 2.7, I'm able to do that in Python 3 but I'm not getting same output in Python 2.7 version code:

Python 3:

import sys
import redis
import io import StringIO
import gzip

redisConn = redis.StrictRedis(host="127.0.0.1", port=6379, db=0)

myValue = "This is test data"
result = gzip.compress(myValue.encode())
redisConn.set("myKey", result)

Python 2.7:

import sys
import redis
import StringIO
import gzip

redisConn = redis.StrictRedis(host="127.0.0.1", port=6379, db=0)
myValue = "This is test data"
out = StringIO.StringIO()
gzip_s = gzip.GzipFile(fileobj=out, mode="w")
result = gzip_s.write(myValue.encode())
redisConn.set("myKey", result)

But Python 2.7 version code is breaking I'm getting an error: 'int' object has no attribute 'encode'

Can someone please help what's the equivalent code of Python 2.7 - my Python 3 version is working as expected.

Thanks for your help in advance.


Solution

  • Python 2 doesn't make the distinction between strings and bytes (even if the gzip stream is open as binary like here). You can write strings in a binary stream without needing to encode it. It has some drawbacks but in your case just remove the .encode() call:

    gzip_s.write(myValue)
    

    for a Python 2/3 agnostic code, I would simply do:

    if bytes is str:
       # python 2, no need to do anything
       pass
    else:
       # python 3+: encode string as bytes
       myValue = myValue.encode()
    
    gzip_s.write(myValue)
    

    EDIT: since you seem to issue a command redisConn.set("myKey", result), don't forget to call:

    gzip_s.close()
    

    before that, or it's not guaranteed that the file is fully flushed.