-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathnosql.py
197 lines (168 loc) · 5.33 KB
/
nosql.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""NoSQL database written in Python"""
# Standard library imports
import socket
import time
HOST = 'localhost'
PORT = 50505
SOCKET = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
STATS = {
'PUT': {
'success': 0,
'error': 0
},
'GET': {
'success': 0,
'error': 0
},
'GETLIST': {
'success': 0,
'error': 0
},
'PUTLIST': {
'success': 0,
'error': 0
},
'INCREMENT': {
'success': 0,
'error': 0
},
'APPEND': {
'success': 0,
'error': 0
},
'DELETE': {
'success': 0,
'error': 0
},
'STATS': {
'success': 0,
'error': 0
},
}
DATA = {}
def parse_message(data):
"""Return a tuple containing the command, the key, and (optionally) the
value cast to the appropriate type."""
try:
command, key, value, value_type = map(str.strip, data.strip().split(';'))
except:
return 'Invalid input! Expected: COMMAND; [KEY]; [VALUE]; [VALUE TYPE]'
if value_type:
if value_type == 'LIST':
value = value.split(',')
elif value_type == 'INT':
value = int(value)
else:
value = None
return command, key, value
def update_stats(command, success):
"""Update the STATS dict with info about if executing *command* was a
*success*"""
if success:
STATS[command]['success'] += 1
else:
STATS[command]['error'] += 1
def handle_put(key, value):
"""Return a tuple containing True and the message to send back to the
client."""
DATA[key] = value
return (True, 'key [{}] set to [{}]'.format(key, value))
def handle_get(key):
"""Return a tuple containing True if the key exists and the message to send
back to the client"""
if key not in DATA:
return (False, 'Error: Key [{}] not found'.format(key))
else:
return (True, DATA[key])
def handle_putlist(key, value):
"""Return a tuple containing True if the command succeeded and the message
to send back to the client"""
return handle_put(key, value)
def handle_getlist(key):
"""Return a tuple containing True if the key contained a list and the
message to send back to the client."""
return_value = exists, value = handle_get(key)
if not exists:
return return_value
elif not isinstance(value, list):
return (False, 'ERROR: Key [{}] contains non-list value ([{}])'.format(
key, value))
else:
return return_value
def handle_increment(key):
"""Return a tuple containing True if the key's value could be incremented
and the message to send back to the client."""
return_value = exists, value = handle_get(key)
if not exists:
return return_value
elif not isinstance(value, int):
return (False, 'ERROR: Key [{}] contains non-list value ([{}])'.format(
key, value))
else:
DATA[key] = value + 1
return (True, 'Key [{}] incremented'.format(key, value))
def handle_append(key, value):
"""Return a tuple containing True if the key's value could be appended to
and the message to send back to the client."""
return_value = exists, list_value = handle_get(key)
if not exists:
return return_value
elif not isinstance(list_value, list):
return (False, 'ERROR: Key [{}] contains non-list value ([{}])'.format(
key, list_value))
else:
DATA[key].append(value)
return (True, 'Key [{}] had value [{}] appended'.format(key, value))
def handle_delete(key):
"""Return a tuple containing True if the key could be deleted and the
message to send back to the client."""
if key not in DATA:
return (
False,
'ERROR: Key [{}] not found and could not be deleted.'.format(key))
else:
del DATA[key]
def handle_stats():
"""Return a tuple containing True and the contents of the STATS dict."""
return (True, str(STATS))
COMMAND_HANDERS = {
'PUT': handle_put,
'GET': handle_get,
'GETLIST': handle_getlist,
'PUTLIST': handle_putlist,
'INCREMENT': handle_increment,
'APPEND': handle_append,
'DELETE': handle_delete,
'STATS': handle_stats,
}
def main():
"""Main entry point for script"""
SOCKET.bind((HOST, PORT))
SOCKET.listen(1)
print('Listening on {}'.format((HOST, PORT)))
while 1:
connection, address = SOCKET.accept()
print('{} New connection from {}'.format(
time.strftime(("%Y/%m/%d %H:%M:%S INFO"), time.localtime()),
address))
data = connection.recv(4096).decode()
command, key, value = parse_message(data)
if command == 'STATS':
response = handle_stats()
elif command in ('GET', 'GETLIST', 'INCREMENT', 'DELETE'):
response = COMMAND_HANDERS[command](key)
elif command in (
'PUT',
'PUTLIST',
'APPEND', ):
response = COMMAND_HANDERS[command](key, value)
else:
response = (False, 'Unknown command type {}'.format(command))
update_stats(command, response[0])
data = '{};\n{}\n'.format(response[0], response[1])
connection.sendall(bytearray(data, 'utf-8'))
connection.close()
if __name__ == '__main__':
main()