# 第7章 Web开发 集成在一起
# 生成HTML的辅助函数,YATE模块
from string import Template
# class string.Template(template)
# 该构造器接受一个参数作为模板字符串。
#
# substitute(mapping, **kwds)
# 执行模板替换,返回一个新字符串。
def start_response(resp="text/html"):
return('Content-type: ' + resp + '\n\n')
# 这个函数需要一个(可选的)字符串作为参数,用它来创建一个CGI "Content-type:"行,参数缺省值是”text/html
def include_header(the_title):
with open('templates/header.html') as headf:
head_text = headf.read()
header = Template(head_text)
return(header.substitute(title=the_title))
# 打开模板文件,读入文件,换入标题
# 需要一个字符串作为参数,用在HTML页面最前面的标题中。页面存储在'templates/header.html'中,可以根据需要替换标题
def include_footer(the_links):
with open('templates/footer.html') as footf:
foot_text = footf.read()
link_string = ''
for key in the_links:
link_string += '<a href="' + the_links[key] + '">' + key + '</a> ' # 在字符串中强制加入空格
footer = Template(foot_text)
return(footer.substitute(links=link_string))
# 打开模板文件,读入文件,换入“the_links”中的链接字典
# 将链接字典转换为一个字符串,然后再换入模板
# 使用一个字符串作为参数,创建HTML页面的尾部。页面存储在'templates/footer.html'中,参数用于动态创建一组链接标记
def start_form(the_url, form_type="POST"):
return('<form action="' + the_url + '" method="' + form_type + '">')
# 返回表单最前面的HTML,允许调用者指定URL,指定方法
def end_form(submit_msg="Submit"):
return('<p></p><input type=submit value="' + submit_msg + '"></form>')
# 返回表单末尾的HTML标记,允许调用者定制表单“submit”按钮文本
def radio_button(rb_name, rb_value):
return('<input type="radio" name="' + rb_name +
'" value="' + rb_value + '"> ' + rb_value + '<br />')
# 给定一个单选钮名和值,创建HTML单选钮
def u_list(items):
u_string = '<ul>'
for item in items:
u_string += '<li>' + item + '</li>'
u_string += '</ul>'
return(u_string)
# 给定一个项列表,转换为HTML无序列表
def header(header_text, header_level=2):
return('<h' + str(header_level) + '>' + header_text +
'</h' + str(header_level) + '>')
# 创建并返回HTML标题标记,默认2级标记。
def para(para_text):
return('<p>' + para_text + '</p>')
# 用HTML段落标记包围一个文本段
print(start_response())
print(start_response("text/plain"))
print(start_response("application/json"))
print(include_header("Welcome to my home on the web!"))
print(include_footer({'Home': '/index.html', 'Select' : '/cgi-bin/select.py'}))
print(include_footer({}))
print(start_form("/cgi-bin/process-athlete.py"))
print(end_form())
print(end_form("Click to Confirm Your Order"))
for fab in ['John', 'Pail', 'George', 'Ringo']:
print(radio_button(fab, fab))
print(u_list(['Life of Brian', 'Holy Grail']))
print(header("Welcome to my home on the web"))
print(header("This is a sub-sub-sub-sub heading", 5))
print(para("Was it worth the wait? We hope it was..."))
[学习笔记]Head First Python 第7章 Web开发 集成在一起 7-2 YATE模块 生成HTML的辅助函数
最新推荐文章于 2025-05-31 14:45:01 发布