ext_redis.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import redis
  2. from redis.connection import Connection, SSLConnection
  3. from redis.sentinel import Sentinel
  4. class RedisClientWrapper(redis.Redis):
  5. """
  6. A wrapper class for the Redis client that addresses the issue where the global
  7. `redis_client` variable cannot be updated when a new Redis instance is returned
  8. by Sentinel.
  9. This class allows for deferred initialization of the Redis client, enabling the
  10. client to be re-initialized with a new instance when necessary. This is particularly
  11. useful in scenarios where the Redis instance may change dynamically, such as during
  12. a failover in a Sentinel-managed Redis setup.
  13. Attributes:
  14. _client (redis.Redis): The actual Redis client instance. It remains None until
  15. initialized with the `initialize` method.
  16. Methods:
  17. initialize(client): Initializes the Redis client if it hasn't been initialized already.
  18. __getattr__(item): Delegates attribute access to the Redis client, raising an error
  19. if the client is not initialized.
  20. """
  21. def __init__(self):
  22. self._client = None
  23. def initialize(self, client):
  24. if self._client is None:
  25. self._client = client
  26. def __getattr__(self, item):
  27. if self._client is None:
  28. raise RuntimeError("Redis client is not initialized. Call init_app first.")
  29. return getattr(self._client, item)
  30. redis_client = RedisClientWrapper()
  31. def init_app(app):
  32. global redis_client
  33. connection_class = Connection
  34. if app.config.get("REDIS_USE_SSL"):
  35. connection_class = SSLConnection
  36. redis_params = {
  37. "username": app.config.get("REDIS_USERNAME"),
  38. "password": app.config.get("REDIS_PASSWORD"),
  39. "db": app.config.get("REDIS_DB"),
  40. "encoding": "utf-8",
  41. "encoding_errors": "strict",
  42. "decode_responses": False,
  43. }
  44. if app.config.get("REDIS_USE_SENTINEL"):
  45. sentinel_hosts = [
  46. (node.split(":")[0], int(node.split(":")[1])) for node in app.config.get("REDIS_SENTINELS").split(",")
  47. ]
  48. sentinel = Sentinel(
  49. sentinel_hosts,
  50. sentinel_kwargs={
  51. "socket_timeout": app.config.get("REDIS_SENTINEL_SOCKET_TIMEOUT", 0.1),
  52. "username": app.config.get("REDIS_SENTINEL_USERNAME"),
  53. "password": app.config.get("REDIS_SENTINEL_PASSWORD"),
  54. },
  55. )
  56. master = sentinel.master_for(app.config.get("REDIS_SENTINEL_SERVICE_NAME"), **redis_params)
  57. redis_client.initialize(master)
  58. else:
  59. redis_params.update(
  60. {
  61. "host": app.config.get("REDIS_HOST"),
  62. "port": app.config.get("REDIS_PORT"),
  63. "connection_class": connection_class,
  64. }
  65. )
  66. pool = redis.ConnectionPool(**redis_params)
  67. redis_client.initialize(redis.Redis(connection_pool=pool))
  68. app.extensions["redis"] = redis_client