本例子的第二部分:用户界面
编写页面视图代码,创建用户界面。根据MVC模式,这里实际是编写一个小型代码库yate.py,其中包括生成HTML的函数,不过HTML代码放在模板中,与python代码分离。导入Python的string模块中Template函数实现模板渲染。
一、Python代码块。
(1)string.Template。
string模块中的template类,用于设定一个固定的字符串格式:'There are $x and $y',$为可替换部分的标识符。便于把内容和格式分开考虑,常用于定制模板。使用方法:s=Template('the name is $x.') ,x='xiaoming'。
(2)代码:
from string import Template
#该函数需要一个字符串(缺省值text/html)作为参数,用来创建一个CGI'content-type'行def start_response(resp='text/html'):
return('content-type:'+resp+'\n\n')
#该函数需要一个字符串作为参数,用在HTML最前面的标题。页面模板代码本身存储在单独的文件'templates/header.html'中,可根据需要通过调用此函数替换标题。
def include_header(the_title):
with open('templates/header.html') as headf: #打开模板文件HTml,读入文件
head_text=headf.read()
header=Template(head_text)
return(header.substitute(title=the_title)) #换入所提供的标题
#该函数用来创建HTML页面的尾部。页面模板代码本身存储在单独的文件'templates/footer.html'中,参数用于动态的创建一组HTML链接标记,参数是一个字典。
def include_footer(the_links):
with open('templates/footer.html') as footf: #打开模板文件HTml,读入文件
foot_text=footf.read()
link_string=''
for key in the_links: # the_links中所提供的HTML链接字典,转换为一个字符串,再换入模板
link_string+='<a href="'+the_links[key]+'">'+key+'</a> '
footer=Template(foot_text)
return(footer.substitute(links=link_string))
#该函数返回表单最前面的HTML。调用时,允许指定URL(表单数据发送到这个URL),还允许指定所使用的方法。
def start_form(the_url,form_type="POST"):
return ('<form action="'+the_url+'"method="'+form_type+'">')
#该函数返回表单末尾的HTML标记。调用时,允许定制表单末尾’Submit‘按钮的文本。
def end_form(submit_msg="Submit"):
return ('<p></p><input type=submit value="'+submit_msg+'">')
#该函数创建一个HTML单选钮,调用参数分别为单选钮名和值,均为必要参数。
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: #for循环实现列表转换功能,每迭代一次向ul元素增加一个Li元素
u_string+='<li>'+item+'</li>'
u_string+='</ul>'
return(u_string)
#该函数创建并返回一个HTML标题标记,默认为2级标题
def header(header_text,header_level=2):
return ('<h'+str(header_level)+'>'+header_text+'<h'+str(header_level)+'>')
#用HTML段落标记包围一个文本段(字符串)
def para(para_text):
return('<p>'+para_text+'</p>')
二、控制器。
(1)webapp目录结构。
创建文件夹webapp,合理组织文件夹结构。cgi-bin:存放所有的代码;data:存放运动员数据文本;templates:存放下载的html模板;images:页面中用到的图像文件。