python - 从瓶中的 for 循环中获取请求命令
问题描述
我要编写一个心算程序。因此,我想在一个页面上表示不同的练习。随机练习来自一个自创的函数。为了比较我想将用户输入('value')输入到 json 文件中的答案。问题在于 for 循环,因为它只是将最后输入的答案写入文件。也许请求命令卡在那里......
我试图在 for 循环下安排输入框,但这不是我想要的样子。
这是它现在的样子:
瓶码:
@route('/excercises')
def excercise():
ex=addsub()
'''addsub is the function for the random excercises and gaves back a bunch of arrays'''
return template('tgtry', ex=ex)
@route('/excercises', method='POST')
def proof_excercise():
with open('addsub.json', 'r') as jsonFile:
a=json.loads(jsonFile.read())
ax=[]
for row in a:
value = request.forms.get('value')
num={"user_ans": value}
ax.append(num)
with open('answer.json', 'w') as jsonFile:
jsonFile.write(json.dumps(ax, indent = 4,sort_keys = False, ensure_ascii=False))
模板:tgtry.tpl
<form action="/excercises" method="post">
<table>
%for row in ex:
<tr>
<td> {{row['ex']}}. </td>
<td> {{row['numb']}} </td>
<td> {{row['sign']}} </td>
<td> {{row['numbb']}} </td>
<td> {{row['signn']}} </td>
<td> {{row['numbbb']}} </td>
<td> {{row['signnn']}} </td>
<td><input name = 'value' type="number" size='12'></td>
</tr>
%end
</table>
<p><input value="proof answer" type="submit"></p>
</form>
解决方案
欢迎来到堆栈溢出!
对于它的价值,我可以解决您提出的直接问题:
问题在于 for 循环,因为它只是将最后输入的答案写入文件。
但请注意,您的设计在其他方面存在缺陷(@Blorgbeard 和@9000 在评论中已经指出)。
由于您有一个多值表单输入,因此您应该使用getall
而不是get
来检索其值。
values = request.forms.getall('value') # returns a list
参考:https ://bottlepy.org/docs/dev/api.html#bottle.MultiDict.getall
推荐阅读
- kubernetes - 如何在 kubernetes 中安装 grafana 插件?
- javascript - Javascript 表达式不理解
- android - 使用纯 RxJava 实现防止快速点击
- r - 函数结果的数据框
- python - 递归地抓取 URL 及其 URL
- kotlin - 为什么 Kotlin 序列在少量元素上表现如此糟糕?
- javascript - 动画后部分显示波段
- javascript - 从 TypeScript 调用 JavaScript 类:Uncaught TypeError ... 不是构造函数
- drupal - 带有 get 参数的 Drupal RSS 视图
- nlp - Python Mallet LDA Errno 2 没有这样的文件或目录