pymemcache

4.0.0 · active · verified Fri Apr 10

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

Install

Imports

Quickstart

This quickstart demonstrates how to connect to a memcached server using `pymemcache.Client`, set a key-value pair with an expiration, and retrieve it. Note that `pymemcache` returns values as bytes, requiring explicit decoding for string values.

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()

view raw JSON →