onehamed
onehamed

Reputation: 127

error list indices must be integers or slices, not str in flask

when I want to check the answers of a random question, flask debugger shows the error: list indices must be integers or slices, not str

my code:

from flask import Flask, render_template, flash, request, redirect, url_for
import random

app = Flask(__name__)
data = [{'q':'question text 1', 'ans':'a1', 'idsh':101}, {'q':'question text 2', 'ans':'a2', 'idsh':102}, {'q':'question text 3', 'ans':'a3', 'idsh':103}, {'q':'question text 4', 'ans':'a4', 'idsh':104}, ]

@app.route("/")
def home():
    return render_template('index.html', data = random.choice(data))


@app.route('/anss')
def answerd():
    if request.args.get('ans') == data['ans']:
        return "yes"
    else:
        return "no"

if __name__ == '__main__':
    app.run()

Upvotes: 0

Views: 105

Answers (1)

Kruspe
Kruspe

Reputation: 645

data = [{'q':'question text 1', 'ans':'a1', 'idsh':101}, ...]

creates a list. Lists can only be accessed by their indices. You have created a list that contains dictionaries. So, data[0] would point to {'q':'question text 1', 'ans':'a1', 'idsh':101}. You could get the answer with data[0]['ans'].

The route answerd() does not know for what question it should validate the answer.

You can either loop through all the dicts within your list and check if data[i]['idsh'] == request.args.get('idsh') or you need to store your data differently, for example like this (assuming idsh is the unique question id):

data = {101: 'a1', ...}

Then you can check for the correct answer like this:

if request.args.get('ans') == data[request.args.get('idsh')]:

Note that you should check if the arguments are valid before using them like this.

Upvotes: 1

Related Questions