How to compress string and store in redis using python

Viewed 1957

I would like to store all my string using Utf8 String Codec with GZIP in python.

I tried below code but compression not happening properly. I don't know what's missing here. How to insert data into redis using gzip compression technique.

After insertion into redis it just printing some number like d49

import redis
import StringIO
import gzip

r = redis.StrictRedis(host='127.0.0.1', port=80, db=0, decode_responses=True)

out = StringIO.StringIO()
with gzip.GzipFile(fileobj=out, mode='w') as f:
    value = f.write('this is my test value')
    r.set('test', value)

Appreciated your help in advance!

Thanks

1 Answers

You can directly use compress() method of gzip.

If you are directly compressing the text string,

import redis
import gzip

r = redis.StrictRedis(host='127.0.0.1', port=80, db=0, decode_responses=True)
text = 'this is my test value'
value = gzip.compress(text.encode())
r.set('test', value)

If you are trying to compress the file,

import redis
import gzip

r = redis.StrictRedis(host='127.0.0.1', port=80, db=0, decode_responses=True)
with open('text.txt', 'rb') as fp:
    value = gzip.compress(fp.read())
    r.set('test', value)
Related