您的位置:首页 > 编程语言 > Python开发

《python》学习笔记(Day6),采用MVC模式的Web应用例子

2016-01-26 13:46 615 查看
导言:MVC(Model-View-Controller),中文名“模型-视图-控制器”,是一个好的Web应用开发所遵循的模式,它有利于把Web应用的代码分解为易于管理的功能模块。

C:Controller负责业务逻辑,将Web应用'粘合'在一起,比如检查用户名是否存在,取出用户信息等,是Python处理URL的函数;

V:View负责显示逻辑,是包含变量的模板,通过简单地替换一些变量,View最终输出的就是用户看到的HTML;

M:Model在哪?Model是用来传给View的,View在替换变量的时候,可以从Model中取出相应的数据。

本例子第一部分:为数据建模。

编写代码,将保存有运动员计时成绩的文本文档组装成一个字典dict,作为Model。
一、对文本数据的格式进行处理的函数。

    运动选手的计时数据存储为文本文档,定义一个函数sanitize,用于处理计时数据,统一格式。

def sanitize(time_string):

    if '-' in time_string:

        splitter='-'

    elif ':' in time_string:

        splitter=':'

    else:

        return(time_string)

    (mins,secs)=time_string.split(splitter)

    return(mins+'.'+secs) 

    创建发布,安装到本地副本,模块名为process。

二、把文本文件数据转换为对象实例的类。

      创建一个继承类athletelist(list),用于把文本文件的计时数据转换为对象实例,定义转换方法,包括相关属性,定义方法top3,用于对实例的计时成绩排序进行处理,保留前三组成绩。

 import process

class athletelist(list):

    def __init__(self,a_name,a_dob=None,a_times=[]):

            list.__init__([])

            self.name=a_name

            self.dob=a_dob

            self.extend(a_times)

    def top3(self):

            return(sorted(set([process.sanitize(st)for st in self]))[0:3])            #  调用函数处理数据格式

    类也可以放在一个模块文件中,创建发布,安装到本地副本,模块名为Athletelist。

三、创建的新模块(名为athletemodel.py)。

    新模块需要实现的功能主要包括:运动员的文本文件数据转换为对象实例,存为字典,然后保存为pickle文件。

    该模块包含的函数主要有:get_coach_data(file.txt);put_to_store(file.txt);get_from_store()。

(1)代码:

import pickle

from Athletelist import athletelist

def get_coach_data(filename):              #读取文本文件数据,返回为Athletelist类的对象实例

    try:

        with open(filename) as jaf:

            data=jaf.readline()

        templ=data.strip().split(',')            #templ 为列表,依次存储运动员姓名、生日、计时成绩

        return(athletelist(templ.pop(0),templ.pop(0),templ))    #返回实例,即get_coach_data(filename)为实例

    except IOError as ioerr:

        print 'File error:'+str(ioerr)

        return(None) 

def put_to_store(files_list):          #将对象实例存到字典中,按选手名索引(键名),保存为pickle文件

    all_athletes={}

    for each_file in files_list:

        ath=get_coach_data(each_file)   # ath 为对象实例,ath.name:姓名,ath.dob:生日,ath:成绩列表 

        all_athletes[ath.name]=ath          #字典中的keys为ath.name,values为ath(成绩列表)

    try:

        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)       #返回字典,即put_to_store()为字典

def get_from_store():                  #读取pickle文件的数据,作为字典供使用

    all_athletes={}

    try:

        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)

  (2)例子:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python web应用