[code] #coding:utf-8 import shelve
from flask import Flask, request, render_template, redirect, escape, Markup from datetime import datetime
application = Flask(name)
DATA_FILE = 'guestbook.dat'
def save_data(name,comment,create_at): """ Save the comment data """ #open the shelve module database File
database = shelve.open(DATA_FILE)
#if there is no greeting list in database, create it.
if 'greeting_list' not in database:
greeting_list = []
else:
#get the greeting_list from database
greeting_list = database['greeting_list']
#append the data into the list top
greeting_list.insert(0, {
'name':name,
'comment':comment,
'create_at':create_at,
})
# update the database
database['greeting_list'] = greeting_list
#close the database file
database.close()
def load_data(): """ Return the comment data saved before """ #open the shelve module database file database = shelve.open(DATA_FILE)
#get the greeting_list. if not ,just return empty list.
greeting_list = database.get('greeting_list',[])
database.close()
return greeting_list
@application.route('/') def index(): """ Top page Use template to show the page """ greeting_list=load_data() return render_template('index.html',greeting_list=greeting_list)
@application.route('/post',methods=['POST']) def post(): """ Comment's target url """ # get the comment data name = request.form.get('name') comment = request.form.get('comments') create_at = datetime.now() save_data(name, comment, create_at) #rediret to the top page return redirect('/')
if name== 'main': #Run the application when the IP address is 0.0.0.0 and the port is 8000
application.run('0.0.0.0',8000,debug=True)
[/code]
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.