aiomcache

0.8.2 · active · verified Fri Apr 17

aiomcache is a minimal pure Python memcached client built for asynchronous applications with `asyncio`. It provides an easy-to-use interface for common memcached operations like set, get, and delete. The current version is 0.8.2, and it is actively maintained within the `aio-libs` project with a moderate release cadence addressing bug fixes and minor features.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize `aiomcache.Client`, set, get, and delete data asynchronously. It uses environment variables for host and port, falling back to localhost:11211, and includes error handling and graceful client closure.

import asyncio
import os
from aiomcache import Client

async def main():
    # Connect to memcached using environment variables or fallbacks
    host = os.environ.get('MEMCACHED_HOST', '127.0.0.1')
    port = int(os.environ.get('MEMCACHED_PORT', '11211'))
    
    # Initialize the client (Client itself is not an awaitable)
    mc = Client(host, port)
    
    key = b"my_async_key"
    value = b"my_async_value"

    try:
        # Set a key-value pair
        await mc.set(key, value)
        print(f"Set '{key.decode()}'")

        # Get the value for the key
        retrieved_value = await mc.get(key)
        if retrieved_value:
            print(f"Retrieved '{key.decode()}': '{retrieved_value.decode()}'")
        else:
            print(f"Key '{key.decode()}' not found.")

        # Delete the key
        await mc.delete(key)
        print(f"Deleted '{key.decode()}'")
        
    except Exception as e:
        print(f"An error occurred: {e}")
    finally:
        # Always close the client connection(s)
        await mc.close()
        print("Client closed.")

if __name__ == "__main__":
    asyncio.run(main())

view raw JSON →