从瓶中的for循环中获取请求命令

时间:2019-06-24 19:18:27

标签: python python-3.x post bottle

我要编写一个心理算术程序。因此,我想在页面上代表不同的练习。随机练习来自一个自我创建的功能。为了比较答案,我想为用户提供输入('value')到json文件中。问题是for循环,因为它只是将最后输入的答案写入文件中。也许请求命令卡在那里...

我试图将输入框安排在for循环下,但这并不是我想要的样子。

这是现在的样子: screenshot of the form

瓶码:

@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>&nbsp;{{row['ex']}}.&nbsp;</td>
             <td>&nbsp;{{row['numb']}}&nbsp;</td>
             <td>&nbsp;{{row['sign']}}&nbsp;</td>
             <td>&nbsp;{{row['numbb']}}&nbsp;</td>
             <td>&nbsp;{{row['signn']}}&nbsp;</td>
             <td>&nbsp;{{row['numbbb']}}&nbsp;</td>
             <td>&nbsp;{{row['signnn']}}&nbsp;</td>
             <td><input name = 'value' type="number" size='12'></td> 
         </tr>
        %end
    </table>
<p><input value="proof answer" type="submit"></p>
</form>

1 个答案:

答案 0 :(得分:0)

欢迎堆栈溢出!

对于它的价值,我可以解决您提出的紧迫问题:

  

问题是for循环,因为它只是将最后输入的答案写入文件中。

但是请注意,您的设计在其他方面存在缺陷(@Blorgbeard和@ 9000已在评论中指出)。

由于具有多值表单输入,因此应使用getall而不是get来检索其值。

values = request.forms.getall('value')  # returns a list

参考:https://bottlepy.org/docs/dev/api.html#bottle.MultiDict.getall