Created
October 30, 2024 11:15
-
-
Save aladagemre/59b70b329bce682189edae5da8dfade7 to your computer and use it in GitHub Desktop.
Export Redis Data from Heroku
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 json | |
import redis | |
client = redis.StrictRedis( | |
host='hostname', | |
port=6379, | |
db=0, | |
password='password', | |
ssl=True, | |
ssl_cert_reqs=None | |
) | |
data = {} | |
# Use scan_iter to iterate over all keys | |
for key in client.scan_iter(): | |
key_str = key.decode("utf-8") | |
key_type = client.type(key_str).decode("utf-8") | |
# Handle different key types | |
if key_type == "string": | |
data[key_str] = client.get(key_str).decode("utf-8") | |
elif key_type == "hash": | |
data[key_str] = {k.decode("utf-8"): v.decode("utf-8") for k, v in client.hgetall(key_str).items()} | |
elif key_type == "list": | |
data[key_str] = [item.decode("utf-8") for item in client.lrange(key_str, 0, -1)] | |
elif key_type == "set": | |
data[key_str] = [item.decode("utf-8") for item in client.smembers(key_str)] | |
elif key_type == "zset": | |
data[key_str] = [ | |
{"member": item[0].decode("utf-8"), "score": item[1]} for item in client.zrange(key_str, 0, -1, withscores=True) | |
] | |
else: | |
data[key_str] = None # Handle unexpected types | |
# Write the data to a JSON file | |
with open("redis_export.json", "w") as file: | |
json.dump(data, file, indent=4) | |
print("Data exported successfully to redis_export.json") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment