pythonmemcachedpython-memcached

Connect to python-memcached using memcached.sock path


How do I connect to Python-memcached using the path to memcached.sock? (Python 2.7)

Memcached comes pre-installed on my host (Webfaction). I have started it and verified that it is running. I also verified that memcached.sock is in my home directory. The documentation says:

"Once your Memcached instance is up and running, you can access it by the path of the socket file (~/memcached.sock) with the software or library which uses memcached."

I have tried this:

import memcache
mc = memcache.Client(['127.0.0.1:11211'], debug=1)
mc.set("some_key", "Some value")

But I get an error on mc.set:

Connection refused.  Marking dead.

I have also tried

mc = memcache.Client('~/memcached.sock', debug=1)

Then the error on mc.set is

Name or service not known.  Marking dead.

Solution

  • I got it working by doing this:

    The setup:

    memcached -d -s /tmp/memcached.sock
    

    The code:

    import memcache
    mc = memcache.Client(['unix:/tmp/memcached.sock'], debug=0)
    mc.set('hello', 'world')
    print(mc.get('hello'))
    

    The full test:

    docker run --rm -t python:3.6 bash -c "$(cat << 'EOF'
    # setup
    apt-get update && \
    apt-get install -y memcached && \
    
    # start memcached
    memcached -u nobody -d -s /tmp/memcached.sock && \
    
    # install the requirements
    pip install python-memcached && \
    
    # run the code
    python <(cat << FOE
    import memcache
    mc = memcache.Client(['unix:/tmp/memcached.sock'], debug=0)
    mc.set('hello', 'world')
    print(mc.get('hello'))
    FOE
    )
    
    EOF
    )"
    

    ... spoilers, it prints out "world"