gpt4 book ai didi

python - Flask 中的 POST 请求和 Content-Type "application/json"无响应

转载 作者:太空宇宙 更新时间:2023-11-03 12:33:56 24 4
gpt4 key购买 nike

我在使用 Flask View 时遇到问题,该 View 应返回内容类型为“application/json”的响应以响应 POST 请求。具体来说,如果我这样做:

curl -v -d 'foo=bar' http://example.org/jsonpost

此 View :

@app.route('/jsonpost', methods=['GET', 'POST'])
def json_post():
resp = make_response('{"test": "ok"}')
resp.headers['Content-Type'] = "application/json"
return resp

我得到某种连接重置:

* About to connect() to example.org port 80 (#0)
* Trying xxx.xxx.xxx.xxx... connected
* Connected to example.org (xxx.xxx.xxx.xxx) port 80 (#0)
> POST /routing/jsonpost HTTP/1.1
> User-Agent: curl/7.19.7 (i486-pc-linux-gnu) libcurl/7.19.7 OpenSSL/0.9.8k zlib/1.2.3.3 libidn/1.15
> Host: example.org
> Accept: */*
> Content-Length: 7
> Content-Type: application/x-www-form-urlencoded
>
< HTTP/1.1 200 OK
< Server: nginx/1.2.4
< Date: Thu, 27 Dec 2012 14:07:59 GMT
< Content-Type: application/json
< Content-Length: 14
< Connection: keep-alive
< Set-Cookie: session="..."; Path=/; HttpOnly
< Cache-Control: public
<
* transfer closed with 14 bytes remaining to read
* Closing connection #0
curl: (18) transfer closed with 14 bytes remaining to read

如果我这样做:

curl -d 'foo=bar' http://example.org/htmlpost

到:

@app.route('/htmlpost', methods=['GET', 'POST'])
def html_post():
resp = make_response('{"test": "ok"}')
resp.headers['Content-Type'] = "text/html"
return resp

我得到了预期的完整响应(200-ok)

{"test": "ok"}

顺便说一下,如果我向同一个 JSON 路由发送 GET 请求:

curl http://example.org/jsonpost

我也得到了预期的回应..有什么想法吗?

最佳答案

感谢 Audrius 的评论,我追踪了 uWSGI 和 nginx 之间的交互问题的可能来源:显然,如果您在请求中收到 POST 数据,您必须在返回响应之前读取它。

例如,这解决了我的问题。

@app.route('/jsonpost', methods=['GET', 'POST'])
def json_post():
if request.method == 'POST':
dummy = request.form
resp = make_response('{"test": "ok"}')
resp.headers['Content-Type'] = "application/json"
return resp

一个不同的解决方案包括将--post-buffering 1传递给uWSGI,如uWSGI's author Roberto De Ioris所述。 .

我仍然不明白为什么当 Content-Type 设置为 "text/html" 时问题没有出现

关于python - Flask 中的 POST 请求和 Content-Type "application/json"无响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14053670/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com