CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pylibmc

Quick and small memcached client for Python

86

1.03x
Overview
Eval results
Files

client-operations.mddocs/

Client Operations

Core memcached operations for data storage, retrieval, and manipulation. These operations form the foundation of memcached functionality and support both single-key and efficient multi-key batch operations.

Capabilities

Data Retrieval

Retrieve values from memcached using keys, with support for default values and CAS (Compare-And-Store) operations.

def get(key: str, default=None):
    """
    Get a single value from memcached.
    
    Parameters:
    - key (str): The key to retrieve
    - default: Value to return if key is not found
    
    Returns:
    Value stored at key, or default if not found
    
    Raises:
    - Error: On connection or protocol errors
    """

def gets(key: str):
    """
    Get a value with its CAS identifier for atomic updates.
    
    Parameters:
    - key (str): The key to retrieve
    
    Returns:
    tuple: (value, cas_id) or (None, None) if key not found
    
    Raises:
    - Error: On connection or protocol errors
    """

def get_multi(keys: list, key_prefix: str = None) -> dict:
    """
    Efficiently retrieve multiple keys in a single operation.
    
    Parameters:
    - keys (list): List of keys to retrieve
    - key_prefix (str, optional): Prefix to add to all keys
    
    Returns:
    dict: Mapping of found keys to their values
    
    Raises:
    - Error: On connection or protocol errors
    """

Data Storage

Store values in memcached with various storage modes and optional compression.

def set(key: str, value, time: int = 0, min_compress_len: int = 0, compress_level: int = -1) -> bool:
    """
    Store a value unconditionally.
    
    Parameters:
    - key (str): Storage key
    - value: Value to store (any serializable type)
    - time (int): Expiration time in seconds (0 = no expiration)
    - min_compress_len (int): Minimum size to trigger compression
    - compress_level (int): Compression level (-1 = default)
    
    Returns:
    bool: True if successful, False otherwise
    
    Raises:
    - Error: On connection or protocol errors
    """

def add(key: str, value, time: int = 0, min_compress_len: int = 0, compress_level: int = -1) -> bool:
    """
    Store a value only if the key doesn't exist.
    
    Parameters:
    - key (str): Storage key
    - value: Value to store (any serializable type)
    - time (int): Expiration time in seconds (0 = no expiration)
    - min_compress_len (int): Minimum size to trigger compression
    - compress_level (int): Compression level (-1 = default)
    
    Returns:
    bool: True if stored, False if key already exists
    
    Raises:
    - Error: On connection or protocol errors
    """

def replace(key: str, value, time: int = 0, min_compress_len: int = 0, compress_level: int = -1) -> bool:
    """
    Store a value only if the key already exists.
    
    Parameters:
    - key (str): Storage key
    - value: Value to store (any serializable type)
    - time (int): Expiration time in seconds (0 = no expiration)
    - min_compress_len (int): Minimum size to trigger compression
    - compress_level (int): Compression level (-1 = default)
    
    Returns:
    bool: True if replaced, False if key doesn't exist
    
    Raises:
    - Error: On connection or protocol errors
    """

def cas(key: str, value, cas: int, time: int = 0) -> bool:
    """
    Store a value using Compare-And-Store for atomic updates.
    
    Parameters:
    - key (str): Storage key
    - value: Value to store (any serializable type)
    - cas (int): CAS identifier from gets() operation
    - time (int): Expiration time in seconds (0 = no expiration)
    
    Returns:
    bool: True if CAS succeeded, False if CAS mismatch
    
    Raises:
    - Error: On connection or protocol errors
    """

def set_multi(keys: dict, time: int = 0, key_prefix: str = None, min_compress_len: int = 0, compress_level: int = -1) -> list:
    """
    Store multiple key-value pairs efficiently.
    
    Parameters:
    - keys (dict): Mapping of keys to values
    - time (int): Expiration time in seconds (0 = no expiration)
    - key_prefix (str, optional): Prefix to add to all keys
    - min_compress_len (int): Minimum size to trigger compression
    - compress_level (int): Compression level (-1 = default)
    
    Returns:
    list: Keys that failed to be stored
    
    Raises:
    - Error: On connection or protocol errors
    """

def add_multi(keys: dict, time: int = 0, key_prefix: str = None, min_compress_len: int = 0, compress_level: int = -1) -> list:
    """
    Add multiple key-value pairs (only if keys don't exist).
    
    Parameters:
    - keys (dict): Mapping of keys to values
    - time (int): Expiration time in seconds (0 = no expiration)
    - key_prefix (str, optional): Prefix to add to all keys
    - min_compress_len (int): Minimum size to trigger compression
    - compress_level (int): Compression level (-1 = default)
    
    Returns:
    list: Keys that already existed and weren't added
    
    Raises:
    - Error: On connection or protocol errors
    """

Data Removal

Remove data from memcached storage.

def delete(key: str) -> bool:
    """
    Delete a key from memcached.
    
    Parameters:
    - key (str): Key to delete
    
    Returns:
    bool: True if deleted, False if key didn't exist
    
    Raises:
    - Error: On connection or protocol errors
    """

def delete_multi(keys: list, key_prefix: str = None) -> bool:
    """
    Delete multiple keys efficiently.
    
    Parameters:
    - keys (list): List of keys to delete
    - key_prefix (str, optional): Prefix to add to all keys
    
    Returns:
    bool: True if all deletes succeeded, False otherwise
    
    Raises:
    - Error: On connection or protocol errors
    """

String Operations

Append or prepend data to existing string values.

def append(key: str, value, time: int = 0, min_compress_len: int = 0, compress_level: int = -1) -> bool:
    """
    Append data to an existing key's value.
    
    Parameters:
    - key (str): Existing key
    - value: Data to append (string or bytes)
    - time (int): New expiration time (0 = unchanged)
    - min_compress_len (int): Minimum size to trigger compression  
    - compress_level (int): Compression level (-1 = default)
    
    Returns:
    bool: True if successful, False if key doesn't exist
    
    Raises:
    - Error: On connection or protocol errors
    """

def prepend(key: str, value, time: int = 0, min_compress_len: int = 0, compress_level: int = -1) -> bool:
    """
    Prepend data to an existing key's value.
    
    Parameters:
    - key (str): Existing key
    - value: Data to prepend (string or bytes)
    - time (int): New expiration time (0 = unchanged)
    - min_compress_len (int): Minimum size to trigger compression
    - compress_level (int): Compression level (-1 = default)
    
    Returns:
    bool: True if successful, False if key doesn't exist
    
    Raises:
    - Error: On connection or protocol errors
    """

Atomic Operations

Atomic increment and decrement operations for numeric values.

def incr(key: str, delta: int = 1) -> int:
    """
    Atomically increment a numeric value.
    
    Parameters:
    - key (str): Key containing numeric value
    - delta (int): Amount to increment by
    
    Returns:
    int: New value after increment
    
    Raises:
    - Error: On connection or protocol errors
    - CacheMiss: If key doesn't exist
    """

def decr(key: str, delta: int = 1) -> int:
    """
    Atomically decrement a numeric value.
    
    Parameters:
    - key (str): Key containing numeric value  
    - delta (int): Amount to decrement by
    
    Returns:
    int: New value after decrement
    
    Raises:
    - Error: On connection or protocol errors
    - CacheMiss: If key doesn't exist
    """

def incr_multi(keys: list, key_prefix: str = None, delta: int = 1):
    """
    Atomically increment multiple numeric values.
    
    Parameters:
    - keys (list): List of keys containing numeric values
    - key_prefix (str, optional): Prefix to add to all keys
    - delta (int): Amount to increment by
    
    Returns:
    None (use get_multi to retrieve new values)
    
    Raises:
    - Error: On connection or protocol errors
    """

Utility Operations

Additional operations for cache management and diagnostics.

def touch(key: str, seconds: int) -> bool:
    """
    Update expiration time of an existing key without changing its value.
    
    Parameters:
    - key (str): Key to update
    - seconds (int): New expiration time from now
    
    Returns:
    bool: True if successful, False if key doesn't exist
    
    Raises:
    - Error: On connection or protocol errors
    """

def hash(key: str) -> int:
    """
    Get the hash value for a key using the configured hash algorithm.
    
    Parameters:
    - key (str): Key to hash
    
    Returns:
    int: Hash value
    """

def flush_all(time: int = 0) -> bool:
    """
    Flush all items from all servers.
    
    Parameters:
    - time (int): Delay before flushing (0 = immediate)
    
    Returns:
    bool: True if successful
    
    Raises:
    - Error: On connection or protocol errors
    """

Mapping Interface

Dictionary-like access to memcached operations.

def __getitem__(key: str):
    """Dict-like key access: value = client[key]"""

def __setitem__(key: str, value):
    """Dict-like key assignment: client[key] = value"""

def __delitem__(key: str):
    """Dict-like key deletion: del client[key]"""

def __contains__(key: str) -> bool:
    """Dict-like membership test: key in client"""

Serialization and Internal Operations

Low-level operations for data serialization and internal client management.

def serialize(value) -> tuple:
    """
    Serialize a Python object for storage in memcached.
    
    Parameters:
    - value: Python object to serialize
    
    Returns:
    tuple: (serialized_data, flags) for memcached storage
    """

def deserialize(data: bytes, flags: int):
    """
    Deserialize data retrieved from memcached back to Python object.
    
    Parameters:
    - data (bytes): Serialized data from memcached
    - flags (int): Flags indicating serialization method used
    
    Returns:
    Deserialized Python object
    """

def clone() -> Client:
    """
    Create a copy of the client with identical configuration.
    Used by connection pools for thread-safe client sharing.
    
    Returns:
    Client: New client instance with same configuration
    """

Usage Examples

Basic Operations

import pylibmc

client = pylibmc.Client(["localhost:11211"])

# Store and retrieve data
client.set("user:123", {"name": "Alice", "age": 30})
user_data = client.get("user:123")

# Use mapping interface
client["config:timeout"] = 300
timeout = client["config:timeout"]
del client["config:timeout"]

Batch Operations

# Efficient multi-key operations
users = {
    "user:1": {"name": "Alice"},
    "user:2": {"name": "Bob"},
    "user:3": {"name": "Charlie"}
}

failed_keys = client.set_multi(users)
if not failed_keys:
    print("All users stored successfully")

# Retrieve multiple users
user_data = client.get_multi(["user:1", "user:2", "user:3"])

Atomic Operations

# Initialize counter
client.set("page_views", "0")

# Increment atomically
new_count = client.incr("page_views", 1)
print(f"Page views: {new_count}")

# Decrement if needed  
client.decr("page_views", 1)

Compare-And-Store

# Atomic update using CAS
value, cas_id = client.gets("user:123")
if value:
    value["last_seen"] = "2024-01-01"
    success = client.cas("user:123", value, cas_id)
    if not success:
        print("Another client modified the value")

Install with Tessl CLI

npx tessl i tessl/pypi-pylibmc

docs

client-operations.md

configuration.md

connection-pooling.md

error-handling.md

index.md

tile.json