Python Flask ValueError:View函数未返回响应

时间:2017-03-04 14:23:39

标签: python json flask

这是我的Flask代码:

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 Post(来自同一台机器):

import requests
import json
dump= '{"on":"true"}'
r = requests.post('http://127.0.0.1:5000', dump)

并收到此错误:

[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

有关为何发生这种情况的任何想法?从一开始在网上阅读我认为这是因为我没有其他的,如果它是一个GET,但我现在无法理解。

2 个答案:

答案 0 :(得分:1)

如果您正在测试直接返回您的帖子请求有效负载,您应该执行jsonify并且flask具有此util功能

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)

然后在您的测试代码中,将Content-Type添加到标题中,(没有这个,request.get_json()无法工作):

dump = '{"on":"true"}'
r = requests.post('http://127.0.0.1:5000', data=dump,
                  headers={'Content-Type': 'application/json'})

答案 1 :(得分:0)

看起来 - 问题在于您的脚本向您的应用程序发出请求。尝试卷曲,如下所示:

$ curl -H "Content-type: application/json" -X POST http://127.0.0.1:5000 -d '{"on":"true"}'

您将得到如下答复:

{
  "on": "true"
}

您的代码(添加了jsonify)应如下所示:

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)