redis.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import socketio
  2. import redis
  3. from redis import asyncio as aioredis
  4. from urllib.parse import urlparse
  5. def parse_redis_service_url(redis_url):
  6. parsed_url = urlparse(redis_url)
  7. if parsed_url.scheme != "redis":
  8. raise ValueError("Invalid Redis URL scheme. Must be 'redis'.")
  9. return {
  10. "username": parsed_url.username or None,
  11. "password": parsed_url.password or None,
  12. "service": parsed_url.hostname or "mymaster",
  13. "port": parsed_url.port or 6379,
  14. "db": int(parsed_url.path.lstrip("/") or 0),
  15. }
  16. def get_redis_connection(redis_url, redis_sentinels, decode_responses=True):
  17. if redis_sentinels:
  18. redis_config = parse_redis_service_url(redis_url)
  19. sentinel = redis.sentinel.Sentinel(
  20. redis_sentinels,
  21. port=redis_config["port"],
  22. db=redis_config["db"],
  23. username=redis_config["username"],
  24. password=redis_config["password"],
  25. decode_responses=decode_responses,
  26. )
  27. # Get a master connection from Sentinel
  28. return sentinel.master_for(redis_config["service"])
  29. else:
  30. # Standard Redis connection
  31. return redis.Redis.from_url(redis_url, decode_responses=decode_responses)
  32. def get_sentinels_from_env(sentinel_hosts_env, sentinel_port_env):
  33. if sentinel_hosts_env:
  34. sentinel_hosts = sentinel_hosts_env.split(",")
  35. sentinel_port = int(sentinel_port_env)
  36. return [(host, sentinel_port) for host in sentinel_hosts]
  37. return []
  38. def get_sentinel_url_from_env(redis_url, sentinel_hosts_env, sentinel_port_env):
  39. redis_config = parse_redis_service_url(redis_url)
  40. username = redis_config["username"] or ""
  41. password = redis_config["password"] or ""
  42. auth_part = ""
  43. if username or password:
  44. auth_part = f"{username}:{password}@"
  45. hosts_part = ",".join(f"{host}:{sentinel_port_env}" for host in sentinel_hosts_env.split(","))
  46. return f"redis+sentinel://{auth_part}{hosts_part}/{redis_config['db']}/{redis_config['service']}"