forked from GauravJayaraj/dsproject_raft
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.py
75 lines (66 loc) · 2.32 KB
/
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
66
67
68
69
70
71
72
73
74
75
import sys, requests
def redirectToLeader(server_address, message):
type = message["type"]
# looping until someone tells he is the leader
while True:
# switching between "get" and "put"
if type == "get":
try:
response = requests.get(server_address,
json=message,
timeout=1)
except Exception as e:
return e
else:
try:
response = requests.put(server_address,
json=message,
timeout=1)
except Exception as e:
return e
# if valid response and an address in the "message" section in reply
# redirect server_address to the potential leader
if response.status_code == 200 and "payload" in response.json():
payload = response.json()["payload"]
if "message" in payload:
server_address = payload["message"] + "/request"
else:
break
else:
break
# if type == "get":
return response.json()
# else:
# return response
# client put request
def put(addr, key, value):
server_address = addr + "/request"
payload = {'key': key, 'value': value}
message = {"type": "put", "payload": payload}
# redirecting till we find the leader, in case of request during election
print(redirectToLeader(server_address, message))
# client get request
def get(addr, key):
server_address = addr + "/request"
payload = {'key': key}
message = {"type": "get", "payload": payload}
# redirecting till we find the leader, in case of request during election
print(redirectToLeader(server_address, message))
if __name__ == "__main__":
if len(sys.argv) == 3:
# addr, key
# get
addr = sys.argv[1]
key = sys.argv[2]
get(addr, key)
elif len(sys.argv) == 4:
# addr, key value
# put
addr = sys.argv[1]
key = sys.argv[2]
val = sys.argv[3]
put(addr, key, val)
else:
print("PUT usage: python3 client.py address 'key' 'value'")
print("GET usage: python3 client.py address 'key'")
print("Format: address: http://ip:port")