Python Binary Memcached Client
A pure Python module for accessing Memcached servers using the binary protocol, including support for SASL authentication and TLS. The current version is 0.31.4, with releases occurring periodically to add features and improvements.
Common errors
-
ModuleNotFoundError: No module named 'bmemcached'
cause The `python-binary-memcached` library is not installed in your current Python environment.fixRun `pip install python-binary-memcached` to install the library. -
AttributeError: 'NoneType' object has no attribute 'init_client' (during client initialization with SASL) OR SASL error: -4 (SASL not initialized)
cause The `pysasl` library, an optional dependency required for SASL authentication, is not installed.fixInstall the `pysasl` library: `pip install pysasl` or `pip install python-binary-memcached[sasl]`. -
socket.error: [Errno 111] Connection refused OR ConnectionError: [Errno 111] Connection refused
cause The Memcached server is either not running, not accessible at the specified host/port, or a firewall is blocking the connection.fixVerify that your Memcached server is running, listening on the correct IP address and port (e.g., `127.0.0.1:11211`), and that no firewall rules are preventing your application from connecting.
Warnings
- gotcha SASL authentication requires the `pysasl` library, which is an optional dependency. If you use SASL and encounter errors like `AttributeError: 'NoneType' object has no attribute 'init_client'` or `SASL error: -4`, `pysasl` is likely missing.
- gotcha For distributing keys across multiple Memcached servers using consistent hashing, explicitly use `bmemcached.DistributedClient`. While `bmemcached.Client` can take multiple servers, it primarily uses a failover strategy (it's internally a `ReplicantClient` since v0.28.0) rather than distributing keys.
- gotcha TLS support was added in v0.29.0. To establish a secure connection, you must explicitly pass `tls_params` to the client constructor. Connections made without `tls_params` will not be encrypted.
Install
-
pip install python-binary-memcached -
pip install python-binary-memcached[sasl]
Imports
- Client
import bmemcached.Client
from bmemcached import Client
- DistributedClient
from bmemcached import DistributedClient
Quickstart
import bmemcached
import os
# Configure client with Memcached server address, optional username, and password
# Use environment variables for sensitive information
servers = ['127.0.0.1:11211']
username = os.environ.get('MEMCACHED_USER', '')
password = os.environ.get('MEMCACHED_PASSWORD', '')
mc = bmemcached.Client(servers, username, password)
# Set a key-value pair
mc.set('my_key', 'Hello, Memcached!')
print(f"Set 'my_key': {mc.get('my_key')}")
# Get a key-value pair
value = mc.get('my_key')
if value:
print(f"Retrieved 'my_key': {value.decode('utf-8')}")
else:
print("'my_key' not found")
# Delete a key
mc.delete('my_key')
print(f"Deleted 'my_key'. Now 'my_key' is: {mc.get('my_key')}")