Memcached in Python

Memcached is a high-performance, open source, distributed memory object caching system. It is an excellent choice for implementing an in-memory key-value store for small chunks of data produced as a result of database calls, API calls, or page rendering. It enables us to easily cache the item, serve the cached item in less than a millisecond, and scale for higher loads. It significantly decreases data access latency, increases throughput, and eases the load off your back-end systems.

In python, the pymemcache client library supports various functionalities like creating a client, using serializers and deserializers, get-set operations and is also widely adopted across the python community.
install it using:
> pip install pymemcache

Getting started:

  1. Establish a connection and get the client:
from pymemcache.client.base import Client
from pymemcache import serde

memcache_client = Client(
   server = 'localhost',
   serializer = serde.python_memcache_serializer,
   deserializer=serde.python_memcache_deserializer)
  1. Use this client to perform various operations like getting, setting and deleting the data from the cache.
    • In the below snippet, the ‘set’ function accepts 3 parameters

      • Key: (type - str) the key against which data is to be cached
      • Value: (type - int, float, string, dict, list, etc) the value to be cached.
      • Expiry: (type - int) expiry of the record in seconds.
memcache_client.set('prime_number',11,100)

print(‘Data from cache: ’,memcache_client.get('prime_numer'))

Output:

Data from cache: '11'
  • Similarly for multi-set and multi-get operations:
memcache_client.set_multi({'even':2,'odd':7,'123':[14,15,16]})

print('Data from cache:',
memcache_client.get_multi(['prime_number','even','random_key']))

Output:

Data from cache: {'prime_number': b'11', 'even': b'2'}

Note: for above example, the record for key ‘random_key’ didn’t exist in the cache so it didn’t return any value against it.

The record can also be deleted from the cache simply by using:

memcache_client.delete('even')
  1. Putting it all together:
from time import sleep
from pymemcache.client.base import Client
from pymemcache import serde

memcache_client = Client(
    server = 'localhost',
    serializer = serde.python_memcache_serializer,
    deserializer = serde.python_memcache_deserializer)

memcache_client.set('prime_number',11,100)
memcache_client.set('ball','tennis',5)
memcache_client.set_multi({'even':2,'123':[14,15,16]})

print(memcache_client.get('prime_number'))
memcache_client.delete('prime_number')
sleep(6)
print(memcache_client.get_multi(['prime_number','even',
                                'random_key','123','ball']))

Output:

11
Sleeping for 6 secs...
{'even': 2, '123': [14, 15, 16]}
Kartik Kapgate

Kartik Kapgate