from wsgiref.simple_server import make_server
from urllib.parse import parse_qs
from html import escape
def app(environ, start_response): # 定义应用
# print(environ)
start_response("200 OK", [("Content_Type", "text/html")])
func = None
for item in routes():
if environ['PATH_INFO'] == item[0]:
func = item[1]
if func:
return [func(environ)]
return [b"<h1>page is not exist</h1>"]
def example(req): # 定义路由对应的处理方法
with open('example.html', 'rb') as f:
lines = f.read()
return lines
def login(req): # 解析post请求参数
# the environment variable CONTENT_LENGTH may be empty or missing
try:
request_body_size = int(req.get('CONTENT_LENGTH', 0))
except (ValueError):
request_body_size = 0
# When the method is POST the variable will be sent
# in the HTTP request body which is passed by the WSGI server
# in the file like wsgi.input environment variable.
request_body = req['wsgi.input'].read(request_body_size)
d = parse_qs(request_body)
print(d) # 返回的dict中的键值对类型 {bytes:[bytes,..]}
user_name = escape(d.get(bytes('user', encoding="utf-8"))[0].decode("utf-8"))
password = escape(d.get(bytes('pwd', encoding="utf-8"))[0].decode("utf-8"))
print(user_name, password)
if user_name == "example" and password == "example":
return example(req)
else:
return b'<h1>username or password is wrong</h1>'
pass
def routes(): # 配置路由
route_pattern = [
("/example", example),
("/login", login)
]
return route_pattern
if __name__ == '__main__':
my_server = make_server('', 9998, app=app) # 创建server实例
my_server.serve_forever() # server监听