1

i have this simple for loop in flask framework

@app.route('/kde')
def fetch_erga():
    cur = mysql.connection.cursor()
    cur.execute("SELECT ergo FROM erga")
    rv = list(cur.fetchall())
    for row in rv:
        stock = str(row[0]['ergo'])
        tsapr += [(stock)]
    return '<h2>' + tsapr + '</h2>'

This leads to jinja crashing and producing the following error in the browser: KeyError: 0

is it an error with key evaluation or the lack of it, or is it just bad looping? Any help would be aprreciated

edit: when running this:

@app.route('/kdef')
def fetch_ergas():
    cur = mysql.connection.cursor()
    cur.execute("SELECT ergo FROM erga")
    rv = list(cur.fetchall())
    return '<h2>' + str(rv) + '</h2>'

i get the following results in the browser

[{'ergo': u'52018'}, {'ergo': u'52019'}, {'ergo': u'63096700'}, {'ergo': u'68003400'}, {'ergo': u'68003501'}, {'ergo': u'69003501'}]

I mean it is not an empty cursor

2 Answers 2

1

KeyError is usually associated with a missing key in a dictionary. If it were me I would start looking into str(row[0]['ergo']). Is it possible one of the row objects in rv does not have 'ergo' key?

maybe if cur.execute("SELECT ergo FROM erga") returns an empty queryset?

EDIT:

every row in rv is a dict type object and you're referencing row[0] but there is no 0 key, change stock = str(row[0]['ergo']) to be stock = str(row['ergo']) and it should work

Sign up to request clarification or add additional context in comments.

5 Comments

thx for your answer. running this: @app.route('/tyropitta') def tyri(): cur = mysql.connection.cursor() cur.execute('SELECT ergo from erga') rv = list(cur.fetchall()) #lista #return '<h1>' + str(rv[0]['ergo']) + '</h1>' return '<h1>' + str(rv) + '</h1>' gives me the following list [{'ergo': u'52018'}, {'ergo': u'52019'}, {'ergo': u'63096700'}, {'ergo': u'68003400'}, {'ergo': u'68003501'}, {'ergo': u'69003501'}]. So the selection cursor is not empty...
[{'ergo': u'52018'}, {'ergo': u'52019'}, {'ergo': u'63096700'}, {'ergo': u'68003400'}, {'ergo': u'68003501'}, {'ergo': u'69003501'}]
@app.route('/tyropitta') def tyri(): cur = mysql.connection.cursor() cur.execute('SELECT ergo from erga') rv = list(cur.fetchall()) #lista #return '<h1>' + str(rv[0]['ergo']) + '</h1>' return '<h1>' + str(rv) + '</h1>'
try editing your question instead of commenting, its' not very legible
Worked like a charm! :)
1

You'd better use the template engine itself for this: http://jinja.pocoo.org/docs/2.10/templates/#block-nesting-and-scope

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.