Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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'>
Add Comment
Please, Sign In to add comment