Python 烧瓶视图返回错误“;查看函数未返回响应;
我有一个视图,它调用一个函数来获得响应。但是,它给出的错误是查看函数没有返回响应。我该如何解决这个问题Python 烧瓶视图返回错误“;查看函数未返回响应;,python,flask,Python,Flask,我有一个视图,它调用一个函数来获得响应。但是,它给出的错误是查看函数没有返回响应。我该如何解决这个问题 from flask import Flask app = Flask(__name__) def hello_world(): return 'test' @app.route('/hello', methods=['GET', 'POST']) def hello(): hello_world() if __name__ == '__main__': app.
from flask import Flask
app = Flask(__name__)
def hello_world():
return 'test'
@app.route('/hello', methods=['GET', 'POST'])
def hello():
hello_world()
if __name__ == '__main__':
app.run(debug=True)
当我试图通过添加一个静态值而不是调用函数来测试它时,它是有效的
@app.route('/hello', methods=['GET', 'POST'])
def hello():
return "test"
以下内容不返回响应:
@app.route('/hello', methods=['GET', 'POST'])
def hello():
hello_world()
你的意思是说
@app.route('/hello', methods=['GET', 'POST'])
def hello():
return hello_world()
请注意,在这个固定函数中添加了
return
。无论在视图函数中执行什么代码,视图都必须返回。如果函数没有返回任何内容,则相当于返回None
,这是无效的响应
除了完全省略return
语句外,另一个常见错误是在某些情况下只返回响应。如果视图基于If
或try
/而具有不同的行为,则需要确保每个分支都返回响应
这个错误的示例不会在GET请求时返回响应,它需要在if
之后返回语句:
@app.route("/hello", methods=["GET", "POST"])
def hello():
if request.method == "POST":
return hello_world()
# missing return statement here
此正确示例在成功和失败时返回响应(并记录失败以进行调试):
@app.route("/hello")
def hello():
try:
return database_hello()
except DatabaseError as e:
app.logger.exception(e)
return "Can't say hello."