A Python API to interact with Redis. It implements common Redis data structures and methods. Useful to separate Redis connection handling from business logic in your projects.
Import the SmartCache object into your file:
>>> from smartcache.redis_communicator import SmartCache
- hset (set a field in a hash):
>>> cache = SmartCache() >>> cache[('test', 'key')] = "value" >>> True
- hget (get a field from a hash):
>>> cache = SmartCache() >>> out = cache[('test', 'key')] >>> b'value'
- exists (check if a key exists):
>>> cache = SmartCache() >>> 'test' in cache >>> True
- hexists (check if a field exists in a hash):
>>> cache = SmartCache() >>> ('test', 'key') in cache >>> True
- sadd and smembers (adding to a set and retrieving all members):
>>> cache = SmartCache() >>> cache['one'] = 'data' # sadd >>> cache['one'] # smembers >>> {b'data'} >>> cache['one'] = 'data1' # sadd >>> cache['one'] # smembers >>> {b'data', b'data1'}
- Adding elements to a list:
>>> cache = SmartCache() >>> cache.rpush('mylist', 'first') # Add to the end >>> cache.rpush('mylist', 'second') >>> cache.lpush('mylist', 'start') # Add to the beginning >>> cache['mylist'] # Get all list elements >>> [b'start', b'first', b'second']
- Removing elements from a list:
>>> cache = SmartCache() >>> cache.lpop('mylist') # Remove from the beginning >>> b'start' >>> cache.rpop('mylist') # Remove from the end >>> b'second' >>> cache['mylist'] >>> [b'first']
By default, SmartCache connects to Redis at:
- Host: 127.0.0.1
- Port: 6379
- DB: 0
You can configure these values:
>>> cache = SmartCache(host='redis.example.com', port=6380, db=1)
SmartCache can be used as a context manager to ensure proper cleanup:
>>> with SmartCache() as cache: ... cache['key'] = 'value' ... print(cache['key']) b'value'