This repository has been archived by the owner on Apr 27, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
13-redis-client.py
executable file
·65 lines (49 loc) · 1.58 KB
/
13-redis-client.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#! /usr/bin/env python
#
# asyncio training (@igalarzab)
# =============================
#
# What:
# Implement a redis client using coroutines
#
import asyncio
import sys
def build_command(command, *arguments):
"""
Build a redis command using RESP
"""
arguments = [arg for arg in arguments if arg is not None]
command = '*%(num_params)d\r\n$%(len_command)d\r\n%(command)s\r\n' % {
'num_params': len(arguments) + 1,
'len_command': len(command),
'command': command
}
for i in range(len(arguments)):
command += '$%(len_param)d\r\n%(param)s\r\n' % {
'len_param': len(arguments[i]),
'param': arguments[i]
}
return command.encode()
@asyncio.coroutine
def get_response(reader):
response = (yield from reader.readline()).decode()
if response[0] in ('+', '-'):
return response[1:]
elif response[0] == '$':
return (yield from reader.readline()).decode()
else:
return '?\n'
@asyncio.coroutine
def main(command, name, value=None):
reader, writer = yield from asyncio.open_connection('127.0.0.1', 6379)
raw_command = build_command(command, name, value)
writer.write(raw_command)
yield from writer.drain()
response = yield from get_response(reader)
print("Command %s sent, received %s" % (command, response), end='')
if __name__ == '__main__':
if len(sys.argv) < 3:
print('Use: %s [get|set] key_name [key_value]' % sys.argv[0])
sys.exit(0)
loop = asyncio.get_event_loop()
loop.run_until_complete(main(sys.argv[1], *sys.argv[2:]))