Guest User

Untitled

a guest
May 22nd, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.55 KB | None | 0 0
  1. import redis # install redis via pip > `python -m pip install redis`
  2. import json
  3.  
  4. # Instantiate redis connection with your local redis instance.
  5. redis_connection = redis.StrictRedis(host="localhost", port=int(6379),
  6. decode_responses=True)
  7.  
  8. """
  9. Caching simple object (flat and one dimentional object) as redis hash.
  10. """
  11. dict_object = {"firstname": "John", "lastname": "Doe"}
  12. type(dict_object) # <class 'dict'>
  13. app.redis_connection.hmset("your_unique_key", dict_object) # cache dict_object as redis hash
  14. cached_data = app.redis_connection.hgetall("your_unique_key") # fetch cached data (hash) from redis
  15. type(cached_data) # <class 'dict'>
  16.  
  17.  
  18. """
  19. Caching nested object as redis hash.
  20. """
  21. dict_object = {
  22. "name": "John Doe",
  23. "social_media_accounts": ["facebook", "twitter", "Instagram"],
  24. "language_proficiency": {
  25. "Python": "9/10",
  26. "Javascript": "7/10",
  27. "Ruby": "8/10"
  28. }
  29. }
  30.  
  31. type(dict_object) # <class 'dict'>
  32. type(dict_object["social_media_accounts"]) # <class 'list'>
  33. type(dict_object["language_proficiency"]) # <class 'dict'>
  34. app.redis_connection.hmset("your_unique_key", dict_object) # cache dict_object as redis hash
  35. cached_data = app.redis_connection.hgetall("your_unique_key") # # fetch cached data (hash) from redis
  36. type(cached_data) # dict
  37. type(cached_data["social_media_accounts"]) # <class 'str'>
  38. type(cached_data["language_proficiency"]) # <class 'str'>
  39.  
  40.  
  41. """
  42. Caching nested object as redis string.
  43. """
  44. dict_object = {
  45. "name": "John Doe",
  46. "social_media_accounts": ["facebook", "twitter", "Instagram"],
  47. "language_proficiency": {
  48. "Python": "9/10",
  49. "Javascript": "7/10",
  50. "Ruby": "8/10"
  51. }
  52. }
  53. stringified_dict_obj = json.dumps(dict_object) # convert your dict object to string
  54.  
  55. type(stringified_dict_obj) # <class 'str'>
  56. app.redis_connection.set("your_unique_key", stringified_dict_obj) # cache stringified dict_object
  57. cached_data = app.redis_connection.get("your_unique_key") # fetch cached data (string) from redis
  58. type(cached_data) # <class 'str'>
  59.  
  60. cached_data_as_dict = json.loads(cached_data) # convert your string cached data to object(dict/JSON)
  61. type(cached_data_as_dict) # <class 'dict'>
  62. type(cached_data_as_dict["social_media_accounts"]) # <class 'list'>
  63. type(cached_data_as_dict["language_proficiency"]) # <class 'dict'>
Add Comment
Please, Sign In to add comment