-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserve.py
61 lines (50 loc) · 1.5 KB
/
serve.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
import os
import urllib
from wsgiref.util import setup_testing_defaults
from wsgiref.simple_server import make_server
choices = ['aaa', 'aab', 'abb', 'bbb']
def choices_get(environ):
data = urllib.parse.parse_qs(environ['QUERY_STRING'])
q = data.get('q', '')
if q:
q = q[0]
selected = data.get('_', [])
html = '\n'.join([
f'<div data-value="{i}">{choice}</div>'
for i, choice in enumerate(choices)
if choice.startswith(q)
and str(i) not in selected
])
if not html:
html = '<div>No result found</div>'
return html, 'text/html'
def static(environ):
ctype = 'text/html'
if len(environ['PATH_INFO']) > 1:
path = environ['PATH_INFO'][1:]
if path.endswith('.css'):
ctype = 'text/css'
elif path.endswith('.js'):
ctype = 'text/javascript'
else:
path = 'index.html'
if os.path.exists(path):
with open(path, 'r') as f:
html = f.read()
else:
html = f'{path} not found'
return html, ctype
def application(environ, start_response):
setup_testing_defaults(environ)
if environ['QUERY_STRING']:
html, ctype = choices_get(environ)
else:
html, ctype = static(environ)
body = html.encode('utf8')
status = '200 OK'
headers = [('Content-type', ctype)]
start_response(status, headers)
return [body]
with make_server('', 8000, application) as httpd:
print("Serving on port 8000...")
httpd.serve_forever()