Memcached

This module provides support for connecting to Memcached servers through the emcache library.

Usage

First install the memcached extra:

$ pip install zayt_contrib[memcached]

Define the configuration properties:

modules = [
    "zayt_contrib.memcached", # (1)
]

[memcached.default] # (2)
nodes = ["localhost:11211"]

[memcached.other] # (3)
nodes = ["unix:///run/memcached.sock"]

Note

  1. Activate the module

  2. Connection will be registered without a name

  3. Connection registered with name “other”

Inject the emcache.Client service:

from typing import Annotated
from emcache import Client as Memcached
from zayt.di import service, Inject


@service
class MyService:
    # default service
    memcached: Annotated[Memcached, Inject]

    # named service
    other_memcached: Annotated[Memcached, Inject("other")]

Example

application/handler.py
from emcache import Client as Memcached
from zayt.web import get

@get
async def index(request, memcached: Memcached):
    if not await memcached.get(b"number"):
        await memcached.set(b"number", b"0")
    number = await memcached.increment(b"number")
    await request.respond_json({"number": number})
configuration/settings.toml
[memcached.default]
nodes = ["localhost:11211"]

Configuration

Memcached can be configured through settings.toml and by providing services.

Services

The extension will look for the following service:

  • emcache.ClusterEvents

Example:

from zayt import di
from emcache import ClusterEvents


class MyClusterEvents(ClusterEvents):
    pass


@di.service
def default_cluster_events() -> ClusterEvents:
    return MyClusterEvents()


@di.service(name="other")
def other_cluster_events() -> ClusterEvents:
    return MyClusterEvents()

Configuration options

[memcached.default]
nodes = ["memcached:11211"]
timeout = 1.0
max_connections = 2
min_connections = 1
purge_unused_connections_after = 60.0
connection_timeout = 5.0
purge_unhealthy_nodes = false
autobatching = false
autobatching_max_keys = 32
ssl = false
ssl_verify = true
ssl_extra_ca = ""
username = ""
password = ""
autodiscovery = false
autodiscovery_poll_interval = 60.0
autodiscovery_timeout = 5.0