程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了Flask中没有POST请求和内容类型“ application / json”的响应大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决Flask中没有POST请求和内容类型“ application / json”的响应?

开发过程中遇到Flask中没有POST请求和内容类型“ application / json”的响应的问题如何解决?下面主要结合日常开发的经验,给出你关于Flask中没有POST请求和内容类型“ application / json”的响应的解决方法建议,希望对你解决Flask中没有POST请求和内容类型“ application / json”的响应有所启发或帮助;

感谢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

如[uWsgi的作者Roberto DeIoris]--post-buffering1所述,一种不同的解决方案涉及传递给uWsgi。

我仍然不明白为什么问题不会在Content-Type设置为"text/HTML"

解决方法

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

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

对此视图:

@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','POST'])
def html_post():
    resp = make_response('{"test": "ok"}')
    resp.headers['Content-Type'] = "text/html"
    return resp

我得到了预期的全面答复(200 ok)

{"test": "ok"}

便说一句,如果我将GET请求发送到同一JSON路由:

curl http://example.org/jsonpost

我也得到了预期的答复。

大佬总结

以上是大佬教程为你收集整理的Flask中没有POST请求和内容类型“ application / json”的响应全部内容,希望文章能够帮你解决Flask中没有POST请求和内容类型“ application / json”的响应所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。