Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compress string and store in redis using python

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

like image 627
learn java Avatar asked Oct 18 '22 03:10

learn java


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)
like image 150
daemon24 Avatar answered Oct 19 '22 22:10

daemon24