Skip to content

Instantly share code, notes, and snippets.

@davide-romanini
Created April 4, 2018 10:02
Show Gist options
  • Save davide-romanini/1132e174d6da630b43eac629bf8213ba to your computer and use it in GitHub Desktop.
Save davide-romanini/1132e174d6da630b43eac629bf8213ba to your computer and use it in GitHub Desktop.
redis backup skeleton
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)
Copy link

ghost commented Apr 4, 2018

For?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment