我无法打印结果。如果我先使用result= request.form
,然后再使用print(result)
,则在烧瓶上工作正常。这会在烧瓶上打印字典。但是使用瓶子不起作用。当我使用type(result)
时说<class 'bottle.FormsDict'>
x.py文件:
from bottle import request, template,route,run,post
@route('/')
def index():
return template('val.html')
@post('/result')
def result():
result=request.forms
print(result) #Unable to print
if __name__ == '__main__':
run(host='localhost',port=8080,debug='True',reloader='True')
val.html文件:
<!DOCTYPE html>
<html>
<body>
<form action="http://localhost:8080/result" method = "POST">
Select a time:
<input type="time" name="usr_time">
<br> <br>
<input type="checkbox" name="A" value="A is on" >A </input>
<br>
<input type="checkbox" name="B" value="B is on" >B </input>
<br>
<input type="checkbox" name="C" value="C is on" >C </input>
<br><br>
<input type="submit"> </input>
</form>
</body>
</html>
result.html文件:
<!doctype html>
<html>
<body>
<table border = 1>
%for key, value in result.items():
<tr>
<th> {{ key }} </th>
<td> {{ value }} </td>
</tr>
%endfor
</table>
</body>
</html>
最佳答案
Bottle的FormsDict类没有定义__str__
或__repr__
方法,因此在打印它时,您仅获得默认表示形式:<bottle.FormsDict object at 0x7fa0661aacf8>
。
但是,您可以像使用普通的Python字典一样访问其键和值:
>>> fd = FormsDict(a=1, b='2')
>>> fd
<bottle.FormsDict object at 0x7fa0661aae80>
>>> fd['a']
1
>>> fd.get('b')
'2'
>>> fd.keys()
dict_keys(['a', 'b'])
>>> list(fd.values())
[1, '2']
>>> list(fd.items())
[('a', 1), ('b', '2')]
如果希望像普通词典一样查看
FormsDict
的内容,则可以将其子类化并提供自己的__repr__
和__str__
方法。此类提供基本的实现*class PrettyFormsDict(FormsDict):
def __repr__(self):
# Return a string that could be eval-ed to create this instance.
args = ', '.join('{}={!r}'.format(k, v) for (k, v) in sorted(self.items()))
return '{}({})'.format(self.__class__.__name__, args)
def __str__(self):
# Return a string that is a pretty representation of this instance.
args = ' ,\n'.join('\t{!r}: {!r}'.format(k, v) for (k, v) in sorted(self.items()))
return '{{\n{}\n}}'.format(args)
>>> PrettyFormsDict = FD.PrettyFormsDict
>>> fd = PrettyFormsDict(a=1, b='2', c='foo')
>>> fd
PrettyFormsDict(a=1, b='2', c='foo')
>>> print(fd)
{
'a': 1 ,
'b': '2' ,
'c': 'foo'
}
*
FormsDict
实际上是一个MultiDict,键可能有几个不同的值。这些值的漂亮印刷留给读者练习。