我有一个视图调用函数来获取响应.但是,它给出了错误View function did not return a response.我该如何解决?
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)
Run Code Online (Sandbox Code Playgroud)
当我尝试通过添加静态值而不是调用函数来测试它时,它可以工作.
@app.route('/hello', methods=['GET', 'POST'])
def hello():
return "test"
Run Code Online (Sandbox Code Playgroud)
Mar*_*eth 46
以下内容未返回响应:
@app.route('/hello', methods=['GET', 'POST'])
def hello():
hello_world()
Run Code Online (Sandbox Code Playgroud)
你的意思是......
@app.route('/hello', methods=['GET', 'POST'])
def hello():
return hello_world()
Run Code Online (Sandbox Code Playgroud)
注意添加return此固定功能.
无论在视图函数中执行什么代码,视图都必须返回一个 Flask 识别为响应的值。如果该函数不返回任何内容,则相当于返回None,这不是有效的响应。
除了return完全省略语句之外,另一个常见错误是仅在某些情况下返回响应。如果您的视图基于 anif或 a try/具有不同的行为except,则需要确保每个分支都返回响应。
这个不正确的示例不会返回对 GET 请求的响应,它需要在 之后的 return 语句if:
@app.route("/hello", methods=["GET", "POST"])
def hello():
if request.method == "POST":
return hello_world()
# missing return statement here
Run Code Online (Sandbox Code Playgroud)
这个正确的例子返回成功和失败的响应(并记录调试失败):
@app.route("/hello")
def hello():
try:
return database_hello()
except DatabaseError as e:
app.logger.exception(e)
return "Can't say hello."
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
28790 次 |
| 最近记录: |