pymemcache
pymemcache is a comprehensive, fast, pure-Python client for memcached. It fully implements the memcached text protocol and supports connections over UNIX sockets, TCP (IPv4 or IPv6), and configurable timeouts. It is currently at version 4.0.0 and maintains an active release cadence.
Warnings
- breaking Version 4.0.0 dropped official support for Python 2.7, 3.4, and 3.5. Ensure your project uses Python 3.7 or newer before upgrading to v4.0.0.
- gotcha `get()` and `get_many()` methods return values as `bytes`, not `str`. You must explicitly decode the retrieved bytes if you expect a string.
- gotcha Memcached keys must adhere to the ASCII protocol and cannot contain spaces, newlines, carriage returns, or null characters by default. Using non-ASCII or illegal characters will raise `MemcacheIllegalInputError`.
- breaking The `expire` argument (previously `time` in `python-memcached`) for set operations now strictly expects an integer representing seconds. Floating-point values are no longer accepted.
- breaking In version 3.0.0, the serialization API was refactored. Instead of separate `serializer` and `deserializer` arguments, client objects now expect a single `serde` object that implements `serialize` and `deserialize` methods.
- gotcha Failing to set `connect_timeout` and `timeout` in client constructors can cause your application to block indefinitely if the memcached server is slow or unavailable. This is crucial for production environments.
Install
-
pip install pymemcache
Imports
- Client
from pymemcache.client.base import Client
- HashClient
from pymemcache.client.hash import HashClient
Quickstart
import os
from pymemcache.client.base import Client
MEMCACHED_HOST = os.environ.get('MEMCACHED_HOST', '127.0.0.1')
MEMCACHED_PORT = int(os.environ.get('MEMCACHED_PORT', '11211'))
# It's highly recommended to set timeouts to prevent blocking indefinitely
client = Client((MEMCACHED_HOST, MEMCACHED_PORT), connect_timeout=1, timeout=0.5)
key = 'my_test_key'
value = 'my_test_value'
# Set a key-value pair
success = client.set(key, value, expire=60) # expire in 60 seconds
print(f"Set '{key}': {value} - Success: {success}")
# Get the value back
retrieved_value = client.get(key)
if retrieved_value:
# pymemcache returns bytes, decode to string if necessary
print(f"Retrieved '{key}': {retrieved_value.decode('utf-8')}")
else:
print(f"Key '{key}' not found or expired.")
client.close()