通过python wsgi构建简易http服务器,其中根目录下的static存放demo.html、diy.css作为演示
wsgi.py:
from wsgiref.simple_server import make_server
class Application(object):
def __init__(self, environ, start_response):
self.start_response = start_response
self.path = environ['PATH_INFO']
def __iter__(self):
if self.path == '/':
status = '200 OK'
response_headers = [('Content-type', 'text/html')]
self.start_response(status, response_headers)
yield '<h1>Hello,World!</h1>'.encode('utf-8')
# /test
elif self.path == '/test':
status = '200 OK'
response_headers = [('Content-type', 'text/html')]
self.start_response(status, response_headers)
yield '<h1>test,ok!</h1>'.encode('utf-8')
# /demo
elif self.path == '/demo':
status = '200 OK'
response_headers = [('Content-type', 'text/html')]
self.start_response(status, response_headers)
file = open("static/demo.html")
res = file.read()
# print(res)
yield res.encode('utf-8')
# *.css
elif self.path.endswith(".css"):
status = '200 OK'
response_headers = [('Content-Type', 'text/css; charset=utf-8')]
self.start_response(status, response_headers)
print('read css file', "static" + self.path)
file = open("static" + self.path)
res = file.read()
yield res.encode('utf-8')
# 404
else:
status = '404 NOT FOUND'
response_headers = [('Content-type', 'text/html')]
self.start_response(status, response_headers)
yield '<h1>404 NOT FOUND</h1>'.encode('utf-8')
if __name__ == "__main__":
app = make_server('127.0.0.1', 8000, Application)
print('Serving HTTP start ...')
app.serve_forever()
static目录下的demo.html:
<html>
<head>
<title>Demo</title>
<link rel="stylesheet" type="text/css" href="diy.css">
</head>
<body>
demo body
<div class="label">bbb</div>
</body>
</html>
static目录下的diy.css:
.label {
color: red;
font-size: 30px;
}