完成基本功能¶
先把功能赶紧搞定!小白立刻开始动手
模板¶
添加记录里有一个表单,如果直接写在python中return出来会很难看!
能不能return一个HTML文件?能!
用模板!
制作模板¶
新建views文件夹,建立add.tpl模板文件,写入Html代码
<html>
<head>
<title>通讯录</title>
</head>
<body>
<form name="add" id="add" method="post">
First name: <input type="text" name="firstname" />
<br />
Last name: <input type="text" name="lastname" />
<br/>
Address: <input type="text" name="address" />
<br/>
Phone: <input type="text" name="phone" />
<br/>
E-mail: <input type="text" name="email" />
<br/>
<input type="submit" value="Submit" />
</form>
</body>
<hmtl>
小白晕掉了……
虽然还是看不懂,反正可以运行了,以后再作研究吧
调用DB¶
小白想到了自己的TextDB函数,这不就是一个很好的DB嘛?
小白将他改造成了一个dict数据库,简化了一下
#-*- coding:utf-8 -*-
try:
import CPickle as pickle
except:
import pickle
try:
f = file('data.tdb')
db = pickle.load(f)
f.close()
except:
db = {}
def save():
f = file('data.tdb','w')
pickle.dump(db, f)
f.close()
然后修改了一下main.py代码
#-*- coding:utf-8 -*-
import bottle
import textdb
@bottle.route('/')
def root():
help='''tiny simple address book:
<br/>- in <a href='/add'>/add</a> appended new address
<br/>- at <a href='/view'>/view</a> check all addresses
'''
return help
@bottle.route('/add')
def add():
return bottle.template('add')
@bottle.route('/add',method = 'POST')
def add():
POST = {}
for i in bottle.request.POST.keys():
POST[i] = bottle.request.POST[i]
key = bottle.request.POST['firstname']
textdb.db[key] = POST
textdb.save()
return "Done! look <a href='/view'>/view</a>"
@bottle.route('/view')
def view():
printlist = ['firstname',
'lastname',
'phone',
'email',
'address']
string = ""
if 0 == len(textdb.db.keys()):
return "new address book,now is empty!"
else:
for i in textdb.db.keys():
for j in printlist:
string += j+": "+textdb.db[i][j]+'<br />'
string += "<br />"
return string
bottle.debug(True)
bottle.run(host = 'localhost', port = 8080,reloader=True)
使用成功!
- 访问网站首页:
- 追加地址:
- 观察数据: