Python implementation of redis API, can be used for testing purposes
—
Redis string data type operations providing full compatibility with Redis string commands. Strings are the most basic Redis data type and can store any binary data including text, numbers, and serialized objects up to 512MB in size.
Core string manipulation functions for setting, getting, and modifying string values.
def set_(
self,
name: KeyT,
value: EncodableT,
ex: Optional[ExpiryT] = None,
px: Optional[ExpiryT] = None,
nx: bool = False,
xx: bool = False,
keepttl: bool = False,
get: bool = False,
exat: Optional[AbsExpiryT] = None,
pxat: Optional[AbsExpiryT] = None
) -> Optional[bytes]: ...
def get(self, name: KeyT) -> Optional[bytes]: ...
def mget(self, keys: Iterable[KeyT]) -> List[Optional[bytes]]: ...
def mset(self, mapping: Mapping[AnyKeyT, EncodableT]) -> ResponseT: ...
def msetnx(self, mapping: Mapping[AnyKeyT, EncodableT]) -> ResponseT: ...
def getset(self, name: KeyT, value: EncodableT) -> Optional[bytes]: ...
def getdel(self, name: KeyT) -> Optional[bytes]: ...
def getex(
self,
name: KeyT,
ex: Optional[ExpiryT] = None,
px: Optional[ExpiryT] = None,
exat: Optional[AbsExpiryT] = None,
pxat: Optional[AbsExpiryT] = None,
persist: bool = False
) -> Optional[bytes]: ...Functions for modifying string content including range operations and concatenation.
def append(self, key: KeyT, value: EncodableT) -> ResponseT: ...
def getrange(self, name: KeyT, start: int, end: int) -> ResponseT: ...
def setrange(self, name: KeyT, offset: int, value: EncodableT) -> ResponseT: ...
def strlen(self, name: KeyT) -> ResponseT: ...
def lcs(
self,
key1: KeyT,
key2: KeyT,
len: bool = False,
idx: bool = False,
minmatchlen: Optional[int] = None,
withmatchlen: bool = False
) -> Union[str, int, Dict[str, Any]]: ...String operations for numeric values including increment, decrement, and floating-point arithmetic.
def incr(self, name: KeyT, amount: int = 1) -> ResponseT: ...
def incrby(self, name: KeyT, amount: int = 1) -> ResponseT: ...
def incrbyfloat(self, name: KeyT, amount: float = 1.0) -> ResponseT: ...
def decr(self, name: KeyT, amount: int = 1) -> ResponseT: ...
def decrby(self, name: KeyT, amount: int = 1) -> ResponseT: ...String setting operations with various conditions and expiration options.
def setnx(self, name: KeyT, value: EncodableT) -> ResponseT: ...
def setex(self, name: KeyT, time: ExpiryT, value: EncodableT) -> ResponseT: ...
def psetex(self, name: KeyT, time_ms: ExpiryT, value: EncodableT) -> ResponseT: ...import fakeredis
client = fakeredis.FakeRedis()
# Basic set and get
client.set('user:1:name', 'Alice')
name = client.get('user:1:name')
print(name.decode()) # 'Alice'
# Set with expiration (seconds)
client.set('session:abc123', 'user_data', ex=3600)
# Set with expiration (milliseconds)
client.set('temp:data', 'value', px=5000)
# Conditional set (only if key doesn't exist)
result = client.set('counter', '0', nx=True)
print(result) # True if set, None if key already exists
# Get and set atomically
old_value = client.getset('config:setting', 'new_value')import fakeredis
client = fakeredis.FakeRedis()
# Set multiple keys at once
client.mset({
'user:1:name': 'Alice',
'user:1:email': 'alice@example.com',
'user:1:age': '30'
})
# Get multiple keys at once
values = client.mget(['user:1:name', 'user:1:email', 'user:1:age'])
for value in values:
if value:
print(value.decode())
# Set multiple keys only if none exist
result = client.msetnx({
'new:key1': 'value1',
'new:key2': 'value2'
})
print(result) # True if all keys were set, False if any already existedimport fakeredis
client = fakeredis.FakeRedis()
# String concatenation
client.set('message', 'Hello')
new_length = client.append('message', ' World')
print(new_length) # 11
print(client.get('message').decode()) # 'Hello World'
# String length
length = client.strlen('message')
print(length) # 11
# Substring operations
client.set('text', 'Hello Redis World')
substring = client.getrange('text', 0, 4)
print(substring.decode()) # 'Hello'
# Replace part of string
client.setrange('text', 6, 'Python')
print(client.get('text').decode()) # 'Hello Python World'import fakeredis
client = fakeredis.FakeRedis()
# Counter operations
client.set('counter', '0')
new_value = client.incr('counter')
print(new_value) # 1
# Increment by specific amount
new_value = client.incrby('counter', 5)
print(new_value) # 6
# Floating point operations
client.set('price', '19.99')
new_price = client.incrbyfloat('price', 5.01)
print(new_price) # 25.0
# Decrement operations
new_value = client.decr('counter')
print(new_value) # 5
new_value = client.decrby('counter', 3)
print(new_value) # 2import fakeredis
client = fakeredis.FakeRedis()
# Get with expiration update
client.set('cached_data', 'important_value', ex=60)
# Get and extend expiration
value = client.getex('cached_data', ex=300) # Extend to 5 minutes
# Get and delete atomically
value = client.getdel('temp_data')
# Key is now deleted, value contains the previous value
# Longest Common Subsequence
client.set('str1', 'abcde')
client.set('str2', 'ace')
lcs_result = client.lcs('str1', 'str2')
print(lcs_result) # 'ace'
# LCS with additional info
lcs_info = client.lcs('str1', 'str2', len=True, idx=True)
print(lcs_info) # Dictionary with matches and indicesimport fakeredis
client = fakeredis.FakeRedis()
# Set only if key doesn't exist
result = client.setnx('unique_id', 'generated_id_123')
print(result) # True if set, False if key already exists
# Set with expiration in seconds
client.setex('session_token', 1800, 'abc123def456') # Expires in 30 minutes
# Set with expiration in milliseconds
client.psetex('short_lived', 5000, 'temporary') # Expires in 5 seconds
# Advanced set with multiple options
result = client.set(
'cache_key',
'cached_value',
ex=3600, # Expire in 1 hour
nx=True, # Only if key doesn't exist
get=True # Return previous value
)import fakeredis
import threading
def worker(client, counter_key, worker_id):
for i in range(100):
count = client.incr(counter_key)
print(f"Worker {worker_id}: {count}")
client = fakeredis.FakeRedis()
client.set('global_counter', '0')
# Simulate multiple threads incrementing counter
threads = []
for i in range(5):
t = threading.Thread(target=worker, args=(client, 'global_counter', i))
threads.append(t)
t.start()
for t in threads:
t.join()
final_count = client.get('global_counter')
print(f"Final count: {final_count.decode()}") # Should be 500import fakeredis
import time
client = fakeredis.FakeRedis()
def get_user_data(user_id):
cache_key = f'user:{user_id}:data'
# Try to get from cache first
cached = client.get(cache_key)
if cached:
return cached.decode()
# Simulate expensive database lookup
time.sleep(0.1)
user_data = f"User {user_id} profile data"
# Cache for 1 hour
client.setex(cache_key, 3600, user_data)
return user_data
# Usage
data1 = get_user_data('123') # Cache miss, slow
data2 = get_user_data('123') # Cache hit, fastInstall with Tessl CLI
npx tessl i tessl/pypi-fakeredisdocs