Memcache Client (PyPI `memcache`)

0.14.0 · active · verified Sat Apr 11

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

Install

Imports

Quickstart

This example demonstrates how to initialize the `memcache` client, set, get, and delete values. It includes recommended practices like using the binary protocol and JSON serialization to avoid common pitfalls.

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).")

view raw JSON →