Python 查看函数没有返回响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14770098/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:23:26  来源:igfitidea点击:

View function did not return a response

pythonsqlflask

提问by saidozcan

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:

我想向 mysql 发送一个查询并获取一个数组。但是无论我怎么做,我都无法让它发挥作用。这是我的代码:

@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?

它总是说,view function did not return a response。我究竟做错了什么?

采纳答案by Martijn Pieters

Flask throws this exception because your authview didn't return anything. Return a response from your authview:

Flask 抛出此异常是因为您的auth视图没有返回任何内容。从您的auth视图中返回响应:

return 'Some response'

To return the MySQL results, perhaps join the rows together into one string:

要返回 MySQL 结果,也许将行连接成一个字符串:

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 usernameparameter, especiallyin a web application. Use SQL parameters instead:

请注意,您确实不想对username参数使用字符串插值,尤其是在 Web 应用程序中。改用 SQL 参数:

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.

现在数据库客户端将为您进行引用并防止 SQL 注入攻击。如果您使用字符串插值,就会发生这种情况

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

(如果这是一个不错的数据库(例如不是 MySQL),则该数据库可以采用现在通用的 SQL 语句并为其创建一个查询计划,然后在多次执行该查询时一次又一次地重复使用该计划;使用字符串插值你d 防止这种情况。)