简体   繁体   中英

get request commands out of a for loop in bottle

I'm going to programm a mental arithmetic program. Therefor I want to represent different excercises on a page. The random excersises came from a self created function. To compare the answers I want to give the users input('value') into a json file. The problem is the for loop because it just write the last entered answer into the file. Maybe the request command stuck there ...

I tried to arrange the input box under the for loop but thats not the way I want it to look like.

Here is a picture of what it looks like now: 表格的截图

Bottlecode:

@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))

Template: 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>

Welcome to Stack Overflow!

For what it's worth, I can fix the immediate problem you asked about:

The problem is the for loop because it just write the last entered answer into the file.

but please note that your design is flawed in other ways (already pointed out by @Blorgbeard and @9000 in comments).

Since you have a multi-valued form input, you should be using getall , not get , to retrieve its value(s).

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM