簡體   English   中英

如何使用python壓縮字符串並在redis中存儲

[英]How to compress string and store in redis using python

我想在python中使用Utf8 String Codec和GZIP存儲我的所有字符串。

我試過下面的代碼,但壓縮沒有正確發生。 我不知道這里缺少什么。 如何使用gzip壓縮技術將數據插入redis。

插入redis之后,只需打印一些像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)

提前感謝您的幫助!

謝謝

你可以直接使用gzip的compress()方法。

如果直接壓縮文本字符串,

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)

如果您嘗試壓縮文件,

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)

暫無
暫無

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

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