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?
A view function is the code you write to respond to requests to your application. Flask uses patterns to match the incoming request URL to the view that should handle it. The view returns data that Flask turns into an outgoing response.
What does return do in flask? The logic that Flask applies to converting return values into response objects is as follows: If a response object of the correct type is returned it's directly returned from the view. If it's a string, a response object is created with that data and the default parameters.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With