首页 > 解决方案 > 从瓶中的 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>&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>

标签: pythonpython-3.xpostbottle

解决方案


欢迎来到堆栈溢出!

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

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

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

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

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

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


推荐阅读