Python Flask ValueError: View function did not return a response
本问题已经有最佳答案,请猛点这里访问。
这是我的烧瓶代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | from flask import Flask from flask import request app = Flask(__name__) @app.route('/', methods=['GET', 'POST']) def signal(): if request.method == 'POST': content = request.get_json() return content else: return 'Hello, world!' if __name__ == '__main__': app.run(debug=True) |
我(从同一台计算机)运行此HTTP日志:
1 2 3 4 | import requests import json dump= '{"on":"true"}' r = requests.post('http://127.0.0.1:5000', dump) |
号
并接收此错误:
1 2 3 4 5 6 7 8 9 10 11 | [2017-03-04 14:18:35,250] ERROR in app: Exception on / [POST] Traceback (most recent call last): File"c:\users\andrew\appdata\local\programs\python\python35-32\lib\site-packages\flask\app.py", line 1982, in wsgi_app response = self.full_dispatch_request() File"c:\users\andrew\appdata\local\programs\python\python35-32\lib\site-packages\flask\app.py", line 1615, in full_dispatch_request return self.finalize_request(rv) File"c:\users\andrew\appdata\local\programs\python\python35-32\lib\site-packages\flask\app.py", line 1630, in finalize_request response = self.make_response(rv) File"c:\users\andrew\appdata\local\programs\python\python35-32\lib\site-packages\flask\app.py", line 1725, in make_response raise ValueError('View function did not return a response') ValueError: View function did not return a response |
有什么关于这为什么会发生的想法吗?从一开始在网上阅读,我认为这是因为我没有其他的东西,以防它是一个得到,但我现在不明白。
如果您正在测试直接返回post-request有效载荷,则应该执行
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | from flask import Flask from flask import request, jsonify app = Flask(__name__) @app.route('/', methods=['GET', 'POST']) def signal(): if request.method == 'POST': content = request.get_json() return jsonify(content) else: return 'Hello, world!' if __name__ == '__main__': app.run(debug=True) |
然后在测试代码中,将
1 2 3 | dump = '{"on":"true"}' r = requests.post('http://127.0.0.1:5000', data=dump, headers={'Content-Type': 'application/json'}) |
号
看起来-问题出在向应用程序发出请求的脚本上。尝试卷曲,如下所示:
1 | $ curl -H"Content-type: application/json" -X POST http://127.0.0.1:5000 -d '{"on":"true"}' |
您将得到如下响应:
1 2 3 | { "on":"true" } |
。
您的代码(添加了jsonify)应该如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | from flask import Flask from flask import request,jsonify app = Flask(__name__) @app.route('/', methods=['GET', 'POST']) def signal(): if request.method == 'POST': content = request.json return jsonify(content) else: return 'Hello, world!' if __name__ == '__main__': app.run(debug=True) |