首先,这里的代码是受Head First Python的启发。瞄了1眼,看了mvc分离的思路以后。自己画了一张草图。
打算做1个 我的书单 演示web
最终效果
1:1个简单的index.py,显示所有书单列表
2:添加或删除书
3:点击一本书,查看内容
记录其中遇到的问题
1:cgi-bin执行需要权限 chmod +x [file or path]
2:cgi-bin执行的脚本文件头部需要加上环境#!/usr/bin/env python
否则,会提示run_cgi 权限错误
今天完成:
模型部分
简单的模版替换(string.Template模版)
首页简单打印一句话
运行截图:
从下往上说起
data格式
book1,watsy,chapter1,chapter2,chapter3,chapter4
__author__ = 'watsy' import pickle # #objectModel # class cwBook(list): def __init__(self, name, author, chapters = []): list.__init__([]) self.name = name self.author = author self.extend(chapters) # #read from files to objects # def readObjectsAndSerialize(file_list, serialize_file): booksDict = {} for bookfile in file_list: #read text file try: with open(bookfile) as bf: datas = bf.readline().strip().split(',') # print datas book = cwBook(datas.pop(0), datas.pop(0), datas) booksDict[book.name] = book except IndexError as err: print ("readObjectsAndSerialize[file err] error : %s" % (err)) pass except IOError as err: print ("readObjectsAndSerialize[read file] error : %s" % (err)) #serialize data if len(booksDict) != 0: try: with open(serialize_file, 'wb') as wdf: pickle.dump(booksDict, wdf) except IOError as err: print ("readObjectsAndSerialize[serialize] error : %s" % (err)) return booksDict # if __name__ == '__main__': # print readObjectsAndSerialize(['../../../data/book1.txt', '../../../data/book2.txt'], '../../../data/books_dump.txt')
__author__ = 'watsy' from string import Template def fun_response(resp = 'text/html'): # return ('Content-Type: %s\r\n\r\n\r\n\r\n' % (resp)) return "Content-Type: text/html\n\n" def fun_html(): return "<html>" def fun_closehtml(): return "</html>" def fun_title(html_title): try: with open('../templete/title.html') as titlefn: title_string = titlefn.read() tem = Template(title_string) return tem.substitute(title=html_title) except IOError as err: print ("fun_title error %s " % (err)) def fun_para(para_string): return "<p>%s</p>" % para_string def fun_img(img_src, width = 200, height = 200): return "<img href='%s' width='%s' height='%s'>" % (img_src, width, height) if __name__ == '__main__': print fun_title('hello world') print fun_para('p tag') print fun_img('http://213.cn/jpg')
#!/usr/bin/env python #must add the python env __author__ = 'watsy' from include.bookModel import cwBook, readObjectsAndSerialize from include.htmlTemplate import * import glob #load books data_files = glob.glob('../../../data/*.txt') # print data_files booksDict = readObjectsAndSerialize(data_files, '../../../data/books_dump.txt') # print booksDict #print html content print fun_response() print fun_html() print fun_title('index') print fun_para('hello world. this is my first web page by python>_<') print fun_closehtml()
__author__ = 'watsy' import BaseHTTPServer, CGIHTTPServer port = 8080 httpd = BaseHTTPServer.HTTPServer(('', port), CGIHTTPServer.CGIHTTPRequestHandler) print ('starting simple_httpd on port :' + str(httpd.server_port)) httpd.serve_forever()