查看函数没有返回响应 [英] View function did not return a response

查看:40
本文介绍了查看函数没有返回响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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]

它总是说,view 函数没有返回响应.我做错了什么?

It always says, view function did not return a response. What am I doing wrong?

推荐答案

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

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

return 'Some response'

要返回 MySQL 结果,可以将行合并为一个字符串:

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])

或者定义一个模板并返回渲染的模板.

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

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,))

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

Now the database client will do the quoting for you and prevent SQL injection attacks. If you use string interpolation, this will happen.

(如果这是一个不错的数据库(例如不是 MySQL),该数据库可以采用现在通用的 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.)

这篇关于查看函数没有返回响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆