Reputation: 2215
I want to send a query to mysql and fetch an array. But however I do it I cannot make it work. Here's my code:
@app.route('/auth',methods=['GET','POST'])
def auth():
username = request.form['username']
password = request.form['password']
cur = db.cursor()
cur.execute("SELECT * FROM tbl_user WHERE username = '%s' " % username)
results = cur.fetchall()
for row in results:
print row[0]
It always says, view function did not return a response
. What am I doing wrong?
Upvotes: 12
Views: 21301
Reputation: 1124948
Flask throws this exception because your auth
view didn't return anything. Return a response from your auth
view:
return 'Some response'
To return the MySQL results, perhaps join the rows together into one string:
cur.execute("SELECT * FROM tbl_user WHERE username = '%s' " % username)
return '\n'.join([', '.join(r) for r in cur])
or define a template and return the rendered template.
Note that you really do not want to use string interpolation for your username
parameter, especially in a web application. Use SQL parameters instead:
cur.execute("SELECT * FROM tbl_user WHERE username = %s", (username,))
Now the database client will do the quoting for you and prevent SQL injection attacks. If you use string interpolation, this will happen.
(If this was a decent database (e.g. not MySQL) the database could take the now-generic SQL statement and create a query plan for it, then reuse the plan again and again as you execute that query multiple times; using string interpolation you'd prevent that.)
Upvotes: 17