-
Notifications
You must be signed in to change notification settings - Fork 0
/
table.py
95 lines (88 loc) · 3.14 KB
/
table.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import socket as Socket
import json
class Table:
name: str
socket: Socket.socket
def __init__(self, name: str, socket: Socket.socket) -> None:
self.name = name
self.socket = socket
def set(self, key: str, val: str):
try:
self.socket.send(bytes(f"SET {key} {val} {self.name}", "utf-8"))
response = ""
while True:
data = self.socket.recv(1024)
data = str(data.decode("utf-8"))
response += data
if response.endswith("\n"):
response = response.strip("\n")
break
return response
except Socket.error as e:
return f"socket error: {e}"
except Exception as e:
return f"exception: {e}"
def setEX(self, key: str, val: str, expiry: int):
try:
self.socket.send(bytes(f"SETEX {key} {val} {self.name} {expiry}", "utf-8"))
response = b""
while True:
data = self.socket.recv(1024)
response += data
if response.endswith("\n") or not data:
response = response.strip("\n")
break
json_data = json.loads(response)
return json_data
except Socket.error as e:
return f"socket error: {e}"
except Exception as e:
return f"exception: {e}"
def delete(self, key: str) -> str:
try:
self.socket.send(bytes(f"DELETE {key} {self.name}", "utf-8"))
response = ""
while True:
data = self.socket.recv(1024)
data = str(data.decode("utf-8"))
response += data
if response.endswith("\n"):
response = response.strip("\n")
break
return data
except Socket.error as e:
return f"socket error: {e}"
except Exception as e:
return f"exception: {e}"
def get(self, key: str) -> str:
try:
self.socket.send(bytes(f"GET {key} {self.name}", "utf-8"))
response = ""
while True:
data = self.socket.recv(1024)
data = str(data.decode("utf-8"))
response += data
if response.endswith("\n"):
response = response.strip("\n")
break
return data
except Socket.error as e:
return f"socket error: {e}"
except Exception as e:
return f"exception: {e}"
def getAll(self) -> dict:
try:
self.socket.send(bytes(f"GET * {self.name}", "utf-8"))
response = ""
while True:
data = self.socket.recv(1024)
data = str(data.decode("utf-8"))
response += data
if response.endswith("\n"):
response = response.strip("\n")
break
return data
except Socket.error as e:
return f"socket error: {e}"
except Exception as e:
return f"exception: {e}"