gpt4 book ai didi

python - 值错误: unsupported format character \'"\' (0x22) when formatting with dict

转载 作者:行者123 更新时间:2023-12-01 04:32:40 26 4
gpt4 key购买 nike

我目前正在阅读 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))

但是,由于某种原因,打印不断失败。我多次尝试删除错误所指出的“”,但无济于事。

有人知道为什么无法打印表单吗?

最佳答案

检查完整代码后,我认为问题出在 replyhtml 中,即 -

    <tr><th>key<td><input type=text name=key value="%(key)">

问题的格式为 - "%(key)" 。您需要指定元素的类型,例如 sd 等,我相信您可能需要 s (对于字符串)。示例-

    <tr><th>key<td><input type=text name=key value="%(key)s">

关于python - 值错误: unsupported format character \'"\' (0x22) when formatting with dict,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32156745/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com