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

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

问题描述

我想发送一个查询到mysql并获取一个数组。但是,我这样做,我不能让它工作。这里是我的代码:

$ $ $ $ $ $ $ c $ @ 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()

结果行:
print row [0]

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

解决方案

Flask抛出这个异常,因为你的 auth 查看没有返回任何东西。返回来自你的 auth 视图的回复:

  return'Some response' 

要返回MySQL结果,可能将这些行连接成一个字符串:

  cur.execute(SELECT * FROM tbl_user WHERE username ='%s'%username)
return'\\\
'.join ([','.join(r)for r in cur])

返回呈现的模板



注意你真的不想在web应用程序中为你的 username 参数,特别是使用字符串插值。改用SQL参数:

  cur.execute(SELECT * FROM tbl_user WHERE username =%s,(username,)) 

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



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

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?

解决方案

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

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

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