Memcache Client (PyPI `memcache`)
The `memcache` library (v0.14.0) is a pure-Python client for Memcached, compatible with Python 3.7+. It is a specific fork of the original `python-memcached` project, designed for Python 3.x compatibility, and has seen sporadic updates (last updated Dec 2023). It is distinct from the `python-memcached` (v1.x.x) series, despite the PyPI `memcache` package linking its homepage to the `python-memcached` GitHub repository, causing significant confusion in the ecosystem.
Warnings
- gotcha The `memcache` PyPI package (v0.14.0) is a specific fork targeting Python 3.7+, distinct from the more commonly maintained `python-memcached` (v1.x.x series), despite sharing historical code and a confusing PyPI homepage link. This often leads to misidentification and incorrect expectations about features or bug fixes.
- gotcha By default, non-string values are serialized using Python's `pickle` module, which can introduce security vulnerabilities if deserializing data from untrusted sources. It also limits interoperability with other memcached clients not using pickle.
- gotcha The client defaults to the older ASCII protocol. For better performance, efficiency, and to enable features like bigger value sizes or SASL authentication, the binary protocol is recommended.
- gotcha Error handling for network issues or server unavailability often results in `None` being returned for `get` operations or `False`/`0` for `set`, without raising specific exceptions. Debugging connection problems can be difficult.
Install
-
pip install memcache
Imports
- Client
import memcache mc = memcache.Client(...)
Quickstart
import memcache
import os
import json
# Ensure a memcached server is running, e.g., on 127.0.0.1:11211.
# Operations will silently fail (returning None/False) if no server is reachable.
# Configuration for memcached servers. Allows environment override.
MEMCACHED_SERVERS = os.environ.get('MEMCACHED_SERVERS', '127.0.0.1:11211').split(',')
# Initialize the client with best practices: binary protocol and JSON serialization.
# This avoids pickle security issues and improves interoperability.
mc = memcache.Client(
MEMCACHED_SERVERS,
debug=0, # Set to 1 for more verbose debugging output
binary=True, # Use binary protocol for better performance and features
serializer=json.dumps,
deserializer=json.loads
)
key = "my_test_key"
value = {"data": "hello world", "count": 123, "status": True}
# Set a value, storing it for 60 seconds
if mc.set(key, value, time=60):
print(f"Set key '{key}' with value: {value}")
else:
print(f"Failed to set key '{key}'. Check server connection.")
# Get a value
retrieved_value = mc.get(key)
if retrieved_value is not None:
print(f"Retrieved key '{key}': {retrieved_value}")
else:
print(f"Failed to retrieve key '{key}' or key not found.")
# Delete a value
if mc.delete(key):
print(f"Deleted key '{key}'.")
else:
print(f"Failed to delete key '{key}' or key was not present.")
# Try getting it again to confirm deletion
retrieved_value_after_delete = mc.get(key)
if retrieved_value_after_delete is None:
print(f"Key '{key}' is confirmed deleted (returned None).")