我目前正在阅读O' Reilly的书“Python编程”。下面是读取货架的代码,并创建一个Web界面,允许您从货架上访问这些值。您可以获取并更新值
'''
Implement a web-based interface for viewing and updating class instances
stored in a shelve; the shelve lives on server (same machine if localhost)
'''
import cgi, sys, os
import shelve, html
shelvename = 'class-shelve'
fieldnames = ('name', 'age', 'job', 'pay')
form = cgi.FieldStorage()
print('Content-type: text/html')
sys.path.insert(0, os.getcwd())
# main html template
replyhtml = """
<html>
<title>People Input Form</title>
<body>
<form method=POST action=peoplecgi.py>
<table>
<tr><th>key<td><input type=text name=key value="%(key)">
$ROWS$
</table>
<p>
<input type=submit value="Fetch", name=action>
<input type=submit value="Update", name=action>
</form>
</body></html>
"""
# insert html for data rows at $ROWS$
rowhtml = '<tr><th>%s<td><input type=text name=%s value="%%(%s)s">\n'
rowshtml = ""
for fieldname in fieldnames:
rowshtml += (rowhtml % ((fieldname,)*3))
replyhtml = replyhtml.replace('$ROWS$', rowshtml)
def htmlize(adict):
new = adict.copy()
for field in fieldnames:
value = new[field]
new[field] = html.escape(repr(value))
return new
def fetchRecord(db, form):
try:
key = form['key'].value
record = db[key]
fields = record.__dict__
fields['key'] = key
except:
fields = dict.fromkeys(fieldnames, '?')
fields['key'] = 'Missing or invalid key!'
return fields
def updateRecord(db, form):
if not 'key' in form:
fields = dict.fromkeys(fieldnames, '?')
fields['key'] = 'Missing key input!'
else:
key = form['key'].value
if key in db:
record = db[key]
else:
from person_start import Person
record = Person(name='?', age='?')
for field in fieldnames:
setattr(record, field, eval(form[field].value))
db[key] = record
fields = record.__dict__
fields['key'] = key
return fields
db = shelve.open(shelvename)
action = form['action'].value if 'action' in form else None
if action == 'Fetch':
fields = fetchRecord(db, form)
elif action == 'Update':
fields = updateRecord(db, form)
else:
fields = dict.fromkeys(fieldnames, '?')
fields['key'] = 'Missing or invalid action!'
db.close()
print(replyhtml % htmlize(fields))
然而,由于某种原因,打印不断失败。我已多次尝试删除&#34;&#34;错误是陈述,但无济于事。
有谁知道为什么这不能打印表格?
答案 0 :(得分:2)
检查完整代码后,我认为问题出在replyhtml
,在行 -
<tr><th>key<td><input type=text name=key value="%(key)">
问题的格式为 - "%(key)"
。您需要指定s
或d
等元素的类型,我相信您可能需要s
(对于字符串)。示例 -
<tr><th>key<td><input type=text name=key value="%(key)s">