-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.py
73 lines (55 loc) · 1.97 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
#!/usr/bin/env python2
from wsgiref.simple_server import make_server
_port = 8080
def error_401(environ, start_response):
response = 'Error 401. Unauthorized.'
status = '401 Unauthorized'
response_headers = [ ('Content-Type', 'text/plain') ]
start_response(status, response_headers)
return [response]
def error_404(environ, start_response):
response = "File not found."
status = '404 Not Found'
response_headers = [ ('Content-Type', 'text/plain') ]
start_response(status, response_headers)
return [response]
def get_type(filename):
if filename.endswith('js'):
return 'text/javascript'
if filename.endswith('css'):
return 'text/css'
if filename.endswith('html'):
return 'text/html'
if filename.endswith('png'):
return 'image/png'
if filename.endswith('jpg'):
return 'image/jpeg'
if filename.endswith('gif'):
return 'image/gif'
if filename.endswith('svg'):
return 'image/svg+xml'
def application(environ, start_response):
response = ''
_filename = environ['PATH_INFO'][1:]
if not _filename:
_filename = 'index.html'
if '..' in _filename or _filename.startswith('..'):
return error_401(environ, start_response)
try:
with open(_filename) as f:
response = f.read()
except IOError:
return error_404(environ, start_response)
status = '200 OK'
response_headers = [ ('Content-Type', get_type(_filename)),
('Content-Length', str(len(response))) ]
start_response(status, response_headers)
return [response]
def get_environ(environ, start_response):
response = [ x + '=' + str(y) + "\n" for x,y in environ.iteritems() ]
start_response('200 OK', [('Content-Type', 'text/plain')])
return response
if __name__ == '__main__':
httpd = make_server('localhost', _port, application)
#httpd = make_server('localhost', _port, get_environ)
httpd.serve_forever()