Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
175 views
in Technique[技术] by (71.8m points)

python - View function did not return a response

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 '
'.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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...