pylibmc

1.6.3 · active · verified Wed Apr 15

pylibmc is a high-performance Python client for memcached, implemented as a C Python extension wrapper around TangentOrg's `libmemcached` library. It offers an API intentionally designed to be close to `python-memcached` for easy drop-in replacement, leveraging features like configurable behaviors, binary protocol, data pickling, and compression. The current version is 1.6.3.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to connect to a memcached server using `pylibmc.Client`, perform basic `set`, `get`, and `delete` operations, and handle optional SASL authentication using environment variables. It highlights setting expiry times and utilizing the binary protocol.

import pylibmc
import os

# Memcached server addresses, can be an environment variable (e.g., for MemCachier).
# For local testing, use ['127.0.0.1:11211']. Multiple servers can be listed.
servers = os.environ.get('MEMCACHIER_SERVERS', '127.0.0.1:11211').split(',')
username = os.environ.get('MEMCACHIER_USERNAME', '')
password = os.environ.get('MEMCACHIER_PASSWORD', '')

# Initialize client. 'binary=True' enables the binary protocol, 'tcp_nodelay' improves performance.
# SASL authentication is used if username and password are provided.
if username and password:
    mc = pylibmc.Client(servers, binary=True, behaviors={"tcp_nodelay": True}, username=username, password=password)
else:
    mc = pylibmc.Client(servers, binary=True, behaviors={"tcp_nodelay": True})

# Basic operations
key = "my_test_key"
value = "Hello from pylibmc!"

# Set a value with an expiry of 60 seconds
success_set = mc.set(key, value, time=60)
print(f"Set '{key}' to '{value}': {success_set}")

# Get the value
retrieved_value = mc.get(key)
print(f"Retrieved '{key}': {retrieved_value}")

# Set multiple values
mc.set_multi({"key1": "value1", "key2": 123})
print(f"Retrieved 'key1': {mc.get('key1')}")

# Delete a key
success_delete = mc.delete(key)
print(f"Deleted '{key}': {success_delete}")
print(f"'{key}' after deletion: {mc.get(key)}")

view raw JSON →