Brainstorm's snippets (1/226)

  One-line redis client

A stupid simple redis client with no dependencies

#!/usr/bin/env python3
import socket

ip = "127.0.0.1"
port = 6379

s = socket.socket()
s.connect((ip, port))

#
# > SET foo 1000
#

key = "foo"
value = "1000"
print('> set %s %s' % (key, value))
s.send(
    ("*3\r\n$3\r\nSET\r\n$%d\r\n%s\r\n$%d\r\n%s\r\n" % (
        len(key),
        key,
        len(value),
        value
    )).encode('utf-8'))
print(s.recv(256))

#
# > RPUSH mylist uno two three
#

listname = "mylist"
items = ["one", "two", "three", ]
print('> rpush %s %s' % (list, ' '.join(items)))
command = "*%d\r\n$5\r\nRPUSH\r\n$%d\r\n%s\r\n" % (
    2 + len(items),
    len(listname),
    listname,
)
for item in items:
    command += '$%d\r\n%s\r\n' % (
        len(item),
        item
    )
s.send(command.encode('utf-8'))
print(s.recv(256))

#
# > PUBLISH mychannel mymessage
#

channel = "mychannel"
message = "mymessage"
print('> publish %s %s' % (channel, message))
s.send(
    ("*3\r\n$7\r\nPUBLISH\r\n$%d\r\n%s\r\n$%d\r\n%s\r\n" % (
        len(channel),
        channel,
        len(message),
        message
    )).encode('utf-8')
)
print(s.recv(256))

s.close()