89 lines
2.3 KiB
Python
89 lines
2.3 KiB
Python
from wsgiref.simple_server import make_server, demo_app
|
|
import time
|
|
from urllib.parse import urlparse
|
|
from io import StringIO
|
|
|
|
HOST_NAME = 'localhost'
|
|
PORT_NUMBER = 6666
|
|
|
|
def handle_html_file_request(filename):
|
|
if filename.startswith('/'):
|
|
filename = filename[1:]
|
|
data = open(filename).read()
|
|
#return [data.encode("utf-8")]
|
|
return [data]
|
|
|
|
def handle_frontpage():
|
|
return handle_html_file_request('index.html')
|
|
#return ["Hello World".encode("utf-8")]
|
|
|
|
def HandleError( PATH_INFO ):
|
|
stdout = StringIO()
|
|
print("requested site \"{}\" not found".format(PATH_INFO), file=stdout)
|
|
print(file=stdout)
|
|
print("time: {}".format(time.asctime()), file=stdout)
|
|
return [stdout.getvalue().encode("utf-8")]
|
|
|
|
def simple_webserver_app(environ, start_response):
|
|
PATH_INFO = environ['PATH_INFO']
|
|
parsed_path = urlparse(PATH_INFO)
|
|
|
|
if environ['REQUEST_METHOD'] == 'GET' :
|
|
start_response("200 OK", [('Content-Type','text/plain; charset=utf-8')])
|
|
|
|
if PATH_INFO=='/' or PATH_INFO=='':
|
|
return handle_frontpage()
|
|
elif PATH_INFO.endswith('.html'):
|
|
return handle_html_file_request(PATH_INFO)
|
|
else:
|
|
return HandleError(PATH_INFO)
|
|
|
|
else:
|
|
assert(0)
|
|
pass
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
httpd = make_server(HOST_NAME,PORT_NUMBER,demo_app)
|
|
#httpd = make_server(HOST_NAME,PORT_NUMBER,simple_webserver_app)
|
|
|
|
print('{} http Server started - http://{}:{}'.format(time.asctime(), HOST_NAME, PORT_NUMBER))
|
|
|
|
try:
|
|
httpd.serve_forever()
|
|
except KeyboardInterrupt:
|
|
pass
|
|
|
|
httpd.close()
|
|
|
|
print('{} http Server started - {}:{}'.format(time.asctime(), HOST_NAME, PORT_NUMBER))
|
|
|
|
|
|
import unittest
|
|
|
|
|
|
class Webserver_UnitTest(unittest.TestCase):
|
|
|
|
def setUp(self):
|
|
pass
|
|
|
|
def test_frontpage(self):
|
|
ret = handle_frontpage()
|
|
self.assertTrue(len(ret)==1)
|
|
|
|
ret = handle_html_file_request('index.html')
|
|
self.assertTrue(len(ret)==1)
|
|
|
|
ret = handle_html_file_request('/index.html')
|
|
self.assertTrue(len(ret)==1)
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|