Registry / database / python-memcached

python-memcached

JSON →
library1.62pypypi✓ verified 25d ago

python-memcached is a pure Python client for the memcached memory cache daemon. It provides a simple interface for storing and retrieving key-value pairs in one or more memcached servers. Currently at version 1.62, the library is stable but largely in maintenance mode, with `pymemcache` being suggested as a more actively developed alternative. Releases are infrequent but the project is still maintained.

pip install python-memcached
INSTALL
IMPORT
SIG · PYTHON-MEMCACHED
P
python-memcached
databasepythonv1.62
Install
1.6s avg
Import
13ms
Disk
16MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v1.62 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.014s · 17.9MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 1.6s · import 0.012s · 18MB
16MB installed
● package 16MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

Client
from memcache import Client
from python_memcached import Client
The top-level package name is `memcache`, not `python_memcached` as one might infer from the PyPI slug.

This quickstart demonstrates how to connect to a Memcached server, set and retrieve string values, store and retrieve Python objects (which are automatically pickled/unpickled), and delete keys using `python-memcached`.

import memcache import os # Connect to a memcached server. Use environment variable for host if available. # Default to localhost:11211 if MEMCACHED_SERVER is not set. MEMCACHED_SERVER = os.environ.get('MEMCACHED_SERVER', '127.0.0.1:11211') mc = memcache.Client([MEMCACHED_SERVER], debug=0) # Set a key-value pair with an expiration time of 60 seconds mc.set("my_key", "Hello, Memcached!", time=60) print(f"Set 'my_key': 'Hello, Memcached!' (expires in 60s)") # Get the value for the key value = mc.get("my_key") print(f"Got 'my_key': {value}") # Set a complex object (will be pickled by default) sample_object = {"name": "Test User", "id": 123} mc.set("user_data", sample_object) print(f"Set 'user_data': {sample_object}") # Retrieve the complex object retrieved_object = mc.get("user_data") print(f"Got 'user_data': {retrieved_object}") # Delete a key mc.delete("my_key") print(f"Deleted 'my_key'.") # Try to get deleted key deleted_value = mc.get("my_key") print(f"Attempt to get 'my_key' after deletion: {deleted_value} (should be None)")
Debug
Known issues
breakingThe `delete()` method's return value changed in version 1.62. It now returns `1` for successful deletion ('DELETED') and `0` for 'NOT_FOUND' or server errors. Previously, its behavior might have been less consistent or different depending on the server response.
fix
Update code to expect `0` for not found/errors and `1` for success when checking `delete()` results.
affects: >=1.62
breakingSupport for Python 2.6, 3.2, and 3.3 was officially dropped in version 1.59.
fix
Upgrade to a supported Python version (e.g., Python 3.6+).
affects: >=1.59
breakingVersion 1.59 introduced changes to how FLAGS are set, which can break compatibility with older `python-memcached` clients, particularly regarding the handling of strings versus bytes. Keys set by v1.58 as strings might be returned as bytes on v1.59, requiring explicit decoding.
fix
Ensure all clients in your system are running compatible `python-memcached` versions. Implement explicit encoding/decoding if encountering `bytes` where `str` is expected, or consider a custom serializer/deserializer.
affects: >=1.59
deprecatedThe `time` argument for the `delete()` method was removed in version 1.58 when not explicitly set, as it is deprecated in the memcached server itself. While `python-memcached` likely handles this gracefully, relying on it is discouraged.
fix
Avoid passing the `time` argument to `delete()`. Memcached `delete` operations are immediate and do not support an expiration time.
affects: >=1.58
gotchaThe `python-memcached` library is in maintenance mode, with `pymemcache` positioned as a more actively developed and feature-rich alternative. New projects or those requiring active enhancements might consider `pymemcache` instead.
fix
Evaluate `pymemcache` for new development. For existing projects, be aware that active feature development for `python-memcached` is minimal.
affects: All
gotchaMemcached itself has limits on key and value sizes: keys can be at most 250 bytes, and values typically have a maximum size of 1MB. Attempting to store larger items will fail.
fix
Design your caching strategy to store smaller, frequently accessed data. For larger objects, consider sharding the data or using an alternative storage solution.
affects: All
gotchaBy default, `python-memcached` uses Python's `pickle` module to serialize and deserialize complex Python objects (like lists, dictionaries, or custom classes) when storing them. This can have security implications if untrusted data is deserialized, and may also be slower or less efficient than custom serialization (e.g., JSON for simple data structures).
fix
For security-sensitive applications, ensure that only trusted data is unpickled. For better interoperability or performance, explicitly serialize/deserialize complex objects using formats like JSON before passing them to `set()` and after receiving them from `get()`.
affects: All
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'memcache'
The `python-memcached` library, which provides the `memcache` module, has not been installed in the current Python environment.
fix
Install the package using pip: `pip install python-memcached`
TypeError: Client() missing 1 required positional argument: 'servers'
The `memcache.Client` constructor was called without providing the mandatory list of memcached server addresses.
fix
Initialize the client with a list of server addresses, for example: `client = memcache.Client(['127.0.0.1:11211'])`
memcache._HostDeadError: Host <host>:<port> is dead.
The memcached server specified in the client configuration is either not running, unreachable, or repeatedly failing to respond to the `python-memcached` client.
fix
Verify that the memcached daemon is running and accessible from the application at the specified host and port, e.g., by running `memcached -d`.
TypeError: set() got an unexpected keyword argument 'expire'
The `set` method of `python-memcached.Client` was called with the `expire` keyword argument, which is specific to `pymemcache`, while `python-memcached` uses `time` for expiration.
fix
Replace `expire` with `time` when specifying the expiration duration, e.g., `client.set('key', 'value', time=30)`
_pickle.UnpicklingError: invalid load key, '\x80'.
The `python-memcached` client attempted to retrieve and deserialize data that was not valid pickled data, often due to storage by a different client or as a raw string.
fix
Ensure consistency in data serialization by either always storing pickled objects with `python-memcached` or manually handling serialization (e.g., JSON) for interoperability with other clients.
Upgrade
Version history
1.62latest on PyPI · released Jan 14, 2024
Audit
Dependencies

No dependency data recorded yet.

Agent activity
13 hits · last 30 days
node
10
Resources
python-memcached — pip install python-memcached · libregistry