创建本地服务器
from http.server import HTTPServer, CGIHTTPRequestHandler # 导入HTTP服务器和CGI模块
port = 8080 # 端口
httpd = HTTPServer(('', port), CGIHTTPRequestHandler) # 创建HTTP服务器
print("Starting simple_httpd on port: " + str(httpd.server_port)) # 显示一条友好消息
httpd.serve_forever() # 启动服务器
生成主页 :
http://localhost:8080/
<html>
<head>
<title>Welcome to Coach Kelly's Website</title>
<link type="text/css" rel="stylesheet" href="coach.css" />
</head>
<body>
<img src="images/coach-head.jpg">
<h1>Welcome to Coach Kelly's Website.</h1>
<p>
For now, all that you'll find here is my athlete's <a href="cgi-bin/generate_list.py">timing data</a>. Enjoy!
</p>
<p>
<strong>See you on the track!</strong>
</p>
</body>
</html>
生成1级页面:
http://localhost:8080/cgi-bin/generate_list.py
import athletemodel
import yate
import glob # 查询文件名列表
data_files = glob.glob("data/*.txt")
athletes = athletemodel.put_to_store(data_files)
print(yate.start_response()) # 响应类型
print(yate.include_header("Coach Kelly's List of Athletes")) # 生成页面标题
print(yate.start_form("generate_timing_data.py")) # 生成表单,提供服务器端程序名
print(yate.para("Select an athlete from the list to work with:")) # 生成段落
for each_athlete in athletes:
print(yate.radio_button("Which_athlete", athletes[each_athlete].name)) # 创建单选按钮
print(yate.end_form("Select")) # 创建提交按钮
print(yate.include_footer({"Home": "/index.html"}))
print(athletemodel)
生成2级页面:
http://localhost:8080/cgi-bin/generate_timing_data.py
import cgi
import athletemodel
import yate
import cgitb # CGI错误跟踪模块
cgitb.enable()
athletes = athletemodel.get_from_store()
form_data = cgi.FieldStorage() # 获取所有表单数据
athlete_name = form_data['Which_athlete'].value # 访问指定数据
print(yate.start_response()) # 响应类型
print(yate.include_header("Coach Kelly's Timing Data")) # 生成页面标题
print(yate.header("Athlete:" + athlete_name + ",DOB: "
+ athletes[athlete_name].dob + "."))
print(yate.para("The top times for this athlete are:")) # 生成段落
print(yate.u_list(athletes[athlete_name].top3()))
print(yate.include_footer({"Home": "/index.html",
"Select another athlete": "generate_list,py"}))