利用python2.7打造1个web站点2

紧接上一文

利用python2.7打造1个web站点2_第1张图片

利用python2.7打造1个web站点2_第2张图片


修改后代码:

bookModel.py

__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)

    def save(self, path=''):

        def writeContent(name,chapter):
            # print name
            # print chapter
            return "%s,%s" % (name, ','.join(chapter))
        try:
            file_path = "%sbook_%s.txt" % (path, self.name)
            with open(file_path, 'w') as fn:
                fn.write(writeContent(self.name, self))
        except IOError as err:
            print ("cwBook [io error] : %s" % (err))


#
#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

#
#read from serialize files
#
def loadObjectsFromSerialize(serialize_file):
    booksDict = {}
    try:
        with open(serialize_file, 'rb') as sff:
            booksDict = pickle.load(sff)
    except IOError as err:
        print ("loadObjectsFromSerialize error : %s", err)
    return booksDict

# if __name__ == '__main__':
#     print readObjectsAndSerialize(['../../../data/book1.txt', '../../../data/book2.txt'], '../../../data/datas.txt')

htmlTemplate.py

__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, code='utf-8'):
    try:
        with open('../templete/title.html') as titlefn:
            title_string = titlefn.read()
            tem = Template(title_string)
            return tem.substitute(title=html_title,charset=code)
    except IOError as err:
        print ("fun_title error %s " % (err))

#<form>
def fun_form(url='',method='post'):
    return "<form action='%s' method='%s'>" % (url, method)

#</form>
def fun_closeform():
    return "</form>"

#<input type='radio'>
def fun_radio_button(name, value):
    return "<input type='radio' name='%s' value='%s'> %s <br>" % (name, value, value)

#<input type='text'>
def fun_text(name, value=''):
    return "<input type='text' name='%s' value='%s'>" % (name, value)

#<input type='submit'>
def fun_submit(name='submit', value='submit'):
    return "<input type='submit' name=%s value=%s>" % (name, value)


def fun_ul_items(name,item_list):
    return_string = "<b>%s</b><ul>" % (name)
    for item in item_list:
        return_string = "%s<li>%s</li>" % (return_string, item)

    return_string = "%s</ul>" % (return_string)

    return return_string


def fun_label(value, name='label'):
    return "<label name='%s'>%s</label>" % (name, value)


#<img>
def fun_img(img_src, width = 200, height = 200):
    return "<img href='%s' width='%s' height='%s'>" % (img_src, width, height)

#<a>
def fun_aLink(url, value):
    return "<a href='%s'>%s</a>" % (url,value)

#<p>
def fun_para(para_string):
    return "<p>%s</p>" % para_string
#<h2>
def fun_header(head_string, level=2):
    return "<h%s>%s</h%s>" % (level,head_string,level)

def fun_hr():
    return "<hr>"
def fun_br():
    return "<br>"

if __name__ == '__main__':
    print fun_title('hello world')
    print fun_para('p tag')
    print fun_img('http://213.cn/jpg')

index.py

#!/usr/bin/env python
# -*- coding: UTF-8 –*-
# 上面这2句很重要
# 缺少第一句,无法执行脚本
# 缺少第二句,无法显示中文

__author__ = 'watsy'
from include.bookModel import cwBook, readObjectsAndSerialize
from include.htmlTemplate import *
import glob
import cgi

#获取from
form_fields = cgi.FieldStorage()

#添加一本书
def addbook(form):
    bookname = form.getvalue('booktitle')
    bookcontent = form.getvalue('bookchapter')
    if bookname and bookcontent:
        #这里要做内容过滤
        book = cwBook(bookname,'',bookcontent.strip().split(","))
        book.save('../data/')
#加载内容
def loadModels():
    #load books
    data_files = glob.glob('../data/book*.txt')
    # print data_files
    # print data_files
    return readObjectsAndSerialize(data_files, '../data/datas.txt')
#显示书籍列表 表单
def showBooListForm(books):
    print fun_form('book.py')
    for book in booksDict.keys():
        print fun_radio_button('book',book)
    print fun_br()
    print fun_submit('look','查看')
    print fun_closeform()
#显示增加书籍 表单
def showAddBookForm():
    print fun_form('','post')

    print fun_para('新增一本书')
    print fun_label('书名')
    print fun_text('booktitle')
    print fun_br()
    print fun_br()

    print fun_label('内容')
    print fun_text('bookchapter')
    print fun_br()
    print fun_br()

    print fun_submit('addbook','新增')
    print fun_closeform()
#html页面
def htmlcontent(books):
    print fun_response()
    print fun_html()
    print fun_title('index')
    print fun_header('这里显示是watsy本人的藏书')

    print fun_hr()
    # form
    showBooListForm(books)
    print fun_hr()
    #add form
    showAddBookForm()

    print fun_hr()

    print fun_closehtml()

#如果是本地提交添加书籍
if form_fields.getvalue('addbook'):
    addbook(form_fields)

#加载数据
booksDict = loadModels()
#输出完整页面
htmlcontent(booksDict)

book.py

#!/usr/bin/env python
__author__ = 'watsy'

import cgi
from include.bookModel import cwBook, loadObjectsFromSerialize
from include.htmlTemplate import *

#get objects
booksDict = loadObjectsFromSerialize('../data/datas.txt')
#get form
form_fields = cgi.FieldStorage()

#print html content
print fun_response()
print fun_html()

print fun_title(form_fields.getvalue('book'))

print fun_aLink('index.py', 'indexPage')

book = booksDict[form_fields.getvalue('book')]
print fun_ul_items(form_fields.getvalue('book'), book)

print fun_closehtml()

simple_httpd.py内容不变

你可能感兴趣的:(利用python2.7打造1个web站点2)