Reputation: 53
I'm unable to print result. This works fine on flask if i use, result= request.form
and then print(result)
. This prints a dictionary on flask. But doesn't work using bottle. When i used type(result)
it says <class 'bottle.FormsDict'>
x.py file:
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 file:
<!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 file:
<!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>
Upvotes: 2
Views: 2716
Reputation: 55824
Bottle's FormsDict class doesn't have a __str__
or __repr__
method defined, so when you print it you just get the default representation: <bottle.FormsDict object at 0x7fa0661aacf8>
.
However you can access its keys and values just like a normal Python dictionary:
>>> 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')]
If you want to be able to view the contents of a FormsDict
like a normal dictionary you can subclass it and provide your own __repr__
and __str__
methods. This class provides basic implementations*
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
is actually a MultiDict, that is it's possible for a key to have several different values. Pretty-printing such values is left as an exercise to the reader.
Upvotes: 6