[学习笔记]Head First Python 第7章 Web开发 集成在一起 7-3生成webapp

本文详细介绍如何使用Python的http.server模块创建本地HTTP服务器,并通过CGI脚本生成动态网页内容,包括主页、一级和二级页面,展示了从服务器搭建到动态内容生成的全过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

创建本地服务器

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)

1级页面

生成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"}))

2级页面

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值