Created
October 6, 2024 06:46
-
-
Save ichux/49c7a9d757cc58973f51e410aebffbed to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
from redis import ConnectionPool, Redis | |
# Setup Redis connection pool | |
POOL = ConnectionPool( | |
host=os.getenv("REDIS_HOST"), | |
port=os.getenv("REDIS_PORT"), | |
db=os.getenv("REDIS_DB"), | |
password=os.getenv("REDISCLI_AUTH"), | |
decode_responses=True, | |
) | |
rs = Redis(connection_pool=POOL) | |
# Function to set a hash in Redis | |
def set_hash(key, data): | |
"""Set multiple key-value pairs in a Redis hash.""" | |
if isinstance(data, dict): | |
rs.hset(key, mapping=data) | |
else: | |
raise ValueError("Data must be a dictionary.") | |
# Function to set a single field in Redis hash | |
def set_field(key, field, value): | |
"""Set a single field in a Redis hash.""" | |
rs.hset(key, field, value) | |
# Function to get the entire hash | |
def get_hash(key): | |
"""Retrieve all fields and values in a Redis hash.""" | |
return rs.hgetall(key) | |
# Function to get a single field from a hash | |
def get_field(key, field): | |
"""Retrieve a specific field value from a Redis hash.""" | |
return rs.hget(key, field) | |
# Example usage | |
set_hash("oneoff", {"a": 1}) | |
set_field("oneoff", "b", 2) | |
print(get_hash("oneoff")) | |
print(get_field("oneoff", "a")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment