-
Notifications
You must be signed in to change notification settings - Fork 3
/
server.py
executable file
·240 lines (176 loc) · 5.99 KB
/
server.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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
#!/usr/bin/env python
# pylint: disable=invalid-name
"""
CherryPy-based webservice daemon with background threads
"""
import threading
import json
import cherrypy
from cherrypy.lib import auth_basic # noqa pylint: disable=unused-import
from cherrypy.process import plugins
import cherrypy_cors
from marshmallow import Schema, fields
USERS = {
'user': 'password',
}
sample_nodes = [
'node1',
'node2',
]
class NodeSchema(Schema):
"""
Marshmallow schema for nodes object
"""
name = fields.String(required=True)
def worker():
"""Background Timer that runs the hello() function every 5 seconds
TODO: this needs to be fixed/optimized. I don't like creating the thread
repeatedly.
"""
while True:
t = threading.Timer(5.0, hello)
t.start()
t.join()
def hello():
"""Output 'hello' on the console"""
print('hello')
class MyBackgroundThread(plugins.SimplePlugin):
"""CherryPy plugin to create a background worker thread"""
def __init__(self, bus):
super().__init__(bus)
self.t = None
def start(self):
"""Plugin entrypoint"""
self.t = threading.Thread(target=worker)
self.t.daemon = True
self.t.start()
# Start at a higher priority that "Daemonize" (which we're not using
# yet but may in the future)
start.priority = 85
class NodesController: \
# pylint: disable=too-few-public-methods
"""Controller for fictional "nodes" webservice APIs"""
@cherrypy.tools.json_out()
def get_all(self):
"""
Handler for /nodes (GET)
"""
return [{'name': name} for name in sample_nodes]
@cherrypy.tools.json_out()
def get(self, name):
"""
Handler for /nodes/<name> (GET)
"""
if name not in sample_nodes:
raise cherrypy.HTTPError(404, f'Node \"{name}\" not found')
return [{'name': name}]
@cherrypy.tools.json_in()
@cherrypy.tools.json_out()
def add_node(self):
"""
Handler for /nodes (POST)
"""
request_data = cherrypy.request.json
data, errors = NodeSchema().load(request_data)
if errors:
# Attempt to format errors dict from Marshmallow
errmsg = ', '.join([f'Key: [{key}], Error: {error}' for key, error in errors.items()])
raise cherrypy.HTTPError(400, f'Malformed POST request data: {errmsg}')
# Successful POST request
return f"TODO: add node [{data['name']}]"
@cherrypy.tools.json_in()
@cherrypy.tools.json_out()
def update_node(self, name):
"""
Handler for /nodes/<name> (PUT)
"""
if name not in sample_nodes:
raise cherrypy.HTTPError(404, f'Node \"{name}\" not found')
# Empty response (http status 204) for successful PUT request
cherrypy.response.status = 204
return ''
@cherrypy.tools.json_in()
@cherrypy.tools.json_out()
def delete_node(self, name): \
# pylint: disable=unused-argument
"""
Handler for /nodes/<name> (DELETE)
"""
# TODO: handle DELETE here
# Empty response (http status 204) for successful DELETE request
cherrypy.response.status = 204
return ''
def jsonify_error(status, message, traceback, version): \
# pylint: disable=unused-argument
"""JSONify all CherryPy error responses (created by raising the
cherrypy.HTTPError exception)
"""
cherrypy.response.headers['Content-Type'] = 'application/json'
response_body = json.dumps(
{
'error': {
'http_status': status,
'message': message,
}
})
cherrypy.response.status = status
return response_body
def validate_password(realm, username, password): \
# pylint: disable=unused-argument
"""
Simple password validation
"""
return username in USERS and USERS[username] == password
if __name__ == '__main__':
cherrypy_cors.install()
MyBackgroundThread(cherrypy.engine).subscribe()
dispatcher = cherrypy.dispatch.RoutesDispatcher()
# /nodes (GET)
dispatcher.connect(name='nodes',
route='/nodes',
action='get_all',
controller=NodesController(),
conditions={'method': ['GET']})
# /nodes/{name} (GET)
#
# Request "/nodes/notfound" (GET) to test the 404 (not found) handler
dispatcher.connect(name='nodes',
route='/nodes/{name}',
action='get',
controller=NodesController(),
conditions={'method': ['GET']})
# /nodes/{name} (POST)
dispatcher.connect(name='nodes',
route='/nodes',
action='add_node',
controller=NodesController(),
conditions={'method': ['POST']})
# /nodes/{name} (PUT)
dispatcher.connect(name='nodes',
route='/nodes/{name}',
action='update_node',
controller=NodesController(),
conditions={'method': ['PUT']})
# /nodes/{name} (DELETE)
dispatcher.connect(name='nodes',
route='/nodes/{name}',
action='delete_node',
controller=NodesController(),
conditions={'method': ['DELETE']})
config = {
'/': {
'request.dispatch': dispatcher,
'error_page.default': jsonify_error,
'cors.expose.on': True,
'tools.auth_basic.on': True,
'tools.auth_basic.realm': 'localhost',
'tools.auth_basic.checkpassword': validate_password,
},
}
cherrypy.tree.mount(root=None, config=config)
cherrypy.config.update({
# 'server.socket_host': '0.0.0.0',
# 'server.socket_port': 8080,
})
cherrypy.engine.start()
cherrypy.engine.block()