Skip to content

Instantly share code, notes, and snippets.

@ryanermita
Created May 17, 2018 14:36
Show Gist options
  • Save ryanermita/6371da82e1e2fd49806148cd3e54b979 to your computer and use it in GitHub Desktop.
Save ryanermita/6371da82e1e2fd49806148cd3e54b979 to your computer and use it in GitHub Desktop.
Storing nested objects in redis sample code which you can use to play around in python and redis.
import redis # install redis via pip > `python -m pip install redis`
import json
# Instantiate redis connection with your local redis instance.
redis_connection = redis.StrictRedis(host="localhost", port=int(6379),
decode_responses=True)
"""
Caching simple object (flat and one dimentional object) as redis hash.
"""
dict_object = {"firstname": "John", "lastname": "Doe"}
type(dict_object) # <class 'dict'>
app.redis_connection.hmset("your_unique_key", dict_object) # cache dict_object as redis hash
cached_data = app.redis_connection.hgetall("your_unique_key") # fetch cached data (hash) from redis
type(cached_data) # <class 'dict'>
"""
Caching nested object as redis hash.
"""
dict_object = {
"name": "John Doe",
"social_media_accounts": ["facebook", "twitter", "Instagram"],
"language_proficiency": {
"Python": "9/10",
"Javascript": "7/10",
"Ruby": "8/10"
}
}
type(dict_object) # <class 'dict'>
type(dict_object["social_media_accounts"]) # <class 'list'>
type(dict_object["language_proficiency"]) # <class 'dict'>
app.redis_connection.hmset("your_unique_key", dict_object) # cache dict_object as redis hash
cached_data = app.redis_connection.hgetall("your_unique_key") # # fetch cached data (hash) from redis
type(cached_data) # dict
type(cached_data["social_media_accounts"]) # <class 'str'>
type(cached_data["language_proficiency"]) # <class 'str'>
"""
Caching nested object as redis string.
"""
dict_object = {
"name": "John Doe",
"social_media_accounts": ["facebook", "twitter", "Instagram"],
"language_proficiency": {
"Python": "9/10",
"Javascript": "7/10",
"Ruby": "8/10"
}
}
stringified_dict_obj = json.dumps(dict_object) # convert your dict object to string
type(stringified_dict_obj) # <class 'str'>
app.redis_connection.set("your_unique_key", stringified_dict_obj) # cache stringified dict_object
cached_data = app.redis_connection.get("your_unique_key") # fetch cached data (string) from redis
type(cached_data) # <class 'str'>
cached_data_as_dict = json.loads(cached_data) # convert your string cached data to object(dict/JSON)
type(cached_data_as_dict) # <class 'dict'>
type(cached_data_as_dict["social_media_accounts"]) # <class 'list'>
type(cached_data_as_dict["language_proficiency"]) # <class 'dict'>
@rosenta
Copy link

rosenta commented Jan 15, 2021

which redis version are you using for this gist?

@Subhraj07
Copy link

I am getting error in app.redis_connection.. Can you please tell me what is app

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