在Flask中获取原始POST负载

时间:2017-02-27 18:41:03

标签: python python-3.x curl post flask

我正在通过cUrl发送文字

curl -X POST -d "Separate account charge and opdeducted fr" http://192.168.50.8/text

并尝试获取

@application.route("/text",methods=['POST'])
def clausIE():
      content = request.data
      text = str(content, encoding="utf-8")

但是得到空字符串,我做错了什么?

注意:我使用Python3.6

2 个答案:

答案 0 :(得分:2)

这实际上不是Flask问题,您使用了错误的curl选项。

-d开关只能用于表单数据。 curl会自动将Content-Type标头设置为application/x-www-form-urlencoded,这意味着Flask将加载原始正文内容并将其解析为表单。您必须使用-H 'Content-Type: application/octet-stream'或其他更适合您数据的mime类型手动设置不同的Content-Type标头。

您还想使用--data-binary,而不是-d--data),因为后者还会尝试将内容解析为键值字段并删除换行符:

curl -X POST -H 'Content-Type: application/octet-stream' \
   --data-binary "Separate account charge and opdeducted fr" \
   http://192.168.50.8/text

答案 1 :(得分:0)

完整的答案似乎分散在一些评论和已接受的回复中。所以总结一下,Python Flask 代码应该看起来像

@application.route("/text",methods=['POST'])
def clausIE():
    content = request.get_data()

    text = str(content, encoding="utf-8") 

    return text

这就是你应该在你的终端上拥有的

curl -X POST --data-binary "Hello World!" http://192.168.50.8/text

在我自己的设置 (OS X) 中,我可以删除 -X POST 并将 URL 括在引号中,这样就可以了

curl --data-binary "Hello World!" "http://192.168.50.8/text"