Created
April 4, 2018 10:02
-
-
Save davide-romanini/1132e174d6da630b43eac629bf8213ba to your computer and use it in GitHub Desktop.
redis backup skeleton
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import redis | |
import json | |
import base64 | |
def test_data(r, items=100): | |
r.flushall() | |
for i in range(1, items): | |
r.set("KEY:{}".format(i), "Nice value to backup {}".format(i)) | |
def dump(r, out): | |
for key in r.scan_iter(): | |
record = {} | |
record[key.decode('utf-8')] = { | |
'value': base64.b64encode(r.dump(key)).decode('utf-8'), | |
'ttl': 0 | |
} | |
ttl = r.pttl(key) | |
if ttl >= 0: | |
record[key.decode('utf-8')]['ttl'] = ttl | |
out.write("{}\n".format(json.dumps(record))) | |
def restore(r, line): | |
record = json.loads(line) | |
for key, dumped in record.items(): | |
print(line) | |
decoded = base64.b64decode(dumped['value']) | |
r.restore(key, dumped['ttl'], decoded) | |
print(r.get(key)) | |
r = redis.StrictRedis(host='redis') | |
test_data(r) | |
with open('backup.dat', 'w+') as out: | |
dump(r, out) | |
r.flushall() | |
with open('backup.dat', 'r') as backup: | |
for line in backup: | |
restore(r, line) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For?