Web应用
好的Web应用应当遵循模型-视图-控制器(Model-View-Controller)模式,即MVC模式,这有助于将Web应用的代码分解为易于管理的功能模块(或组件):
Web应用
在Web上运行的一个程序
Web请求
从Web浏览器发送到Web服务器
Web响应
从Web服务器发送到Web浏览器,作为对Web请求的响应。
为数据建模
Web服务器需要存储数据的一个副本,在这里数据就是文件。
启动这个Web应用时,需要把文本文件中的数据转换为AtheleteList对象实例,存储在一个字典中(按选手名索引),然后保存为一个pickle文件,将这个功能放入put_to_store()函数中。
这个Web应用运行时,pickle文件中的数据可以作为一个字典供应用使用,将这个功能放入get_from_store()函数中。
import pickle
#意思是从athletelist.py中导入AthleteList
from athletelist import AthleteList
def get_coach_data(filename):
try:
with open(filename) as f:
data = f.readline()
templ = data.strip().split(',')
return(AthleteList(templ.pop(0), templ.pop(0), templ))
except IOError as ioerr:
print('File error (get_coach_data): ' + str(ioerr))
return(None)
def put_to_store(files_list):
all_athletes = {}
#定义字典,用于存储运动员对象
for each_file in files_list:
#get_coach_data(each_file)打开文件列表中的每一个文件,
#并将其转换成AthleteList对象。
#最后,将AthleteList对象存入all_athletes字典。
ath = get_coach_data(each_file)
all_athletes[ath.name] = ath
try:
#打开athletes.pickle文件,将字典 all_athletes存入其中。
with open('athletes.pickle', 'wb') as athf:
pickle.dump(all_athletes, athf)
except IOError as ioerr:
print('File error (put_and_store): ' + str(ioerr))
return(all_athletes)
def get_from_store():
all_athletes = {}
try:
#打开athletes.pickle文件,它是一个字典
#然后,将其赋值给字典all_athletes。
with open('athletes.pickle', 'rb') as athf:
all_athletes = pickle.load(athf)
except IOError as ioerr:
print('File error (get_from_store): ' + str(ioerr))
return(all_athletes)
dir() 函数不带参数时,返回当前范围内的变量、方法和定义的类型列表;带参数时,返回参数的属性、方法列表。如果参数包含方法dir(),该方法将被调用。如果参数不包含dir(),该方法将最大限度地收集参数信息。
使用dir()确认导入成功
创建一个要处理的文件列表,然后调用put_to_store()函数将文件列表中的数据转换为一个字典,存储在一个pickle中:
使用数据字典中现有的数据来显示各个选手的名字和出生日期