-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.py
executable file
·56 lines (48 loc) · 1.47 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
#!/usr/bin/env python3
import os
from wsgiref.simple_server import make_server
from wsgiref.util import request_uri
from urllib.parse import urlparse
from util import CommandError, import_class
def route_request(env, start_response):
node = env['DFS_NODE_CLASS']
uri = request_uri(env).rstrip('/')
path = urlparse(uri).path
try:
command, deserialize, serialize = node.HANDLERS[path]
except KeyError:
start_response(
'404 Not Found',
[('Content-type', 'text/plain')],
)
return [b'']
args = deserialize(
env['wsgi.input'],
int(env.get('CONTENT_LENGTH', 0) or 0),
env['REMOTE_ADDR'],
)
try:
resp = command(node, *args)
except CommandError as e:
start_response(
'400 Bad Request',
[('Content-type', 'text/plain')],
)
return [str(e).encode('utf-8')]
start_response(
'200 OK',
[('Content-type', 'application/octet-stream')],
)
return [serialize(resp)]
if __name__ == '__main__':
node_cls = import_class(os.environ['DFS_NODE_CLASS'])
node = node_cls(*node_cls.get_args(os.environ))
def wsgi_app(env, start_response):
env['DFS_NODE_CLASS'] = node
return route_request(env, start_response)
with make_server(
os.environ.get('DFS_HOST', '0.0.0.0'),
int(os.environ.get('DFS_PORT', '8180')),
wsgi_app,
) as server:
server.serve_forever()