[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]
1
zh826256645 2018-11-24 17:33:45 +08:00
额,不知道怎么帮你好,多看看书吧
|
2
masana OP |