Flask或Werkzeug / 0.9.4打破POST数据

时间:2013-12-04 17:16:07

标签: python json flask werkzeug flask-restful

我发现了一些Flask-restful的行为,我认为Werkzeug / 0.9.4我不明白。当我尝试POST包含“=”的有效JSON时,似乎使用Multidict会破坏我的数据。

这是我的测试JSON:

{
    "alert": {
        "@id": "90",
        "action": "hoojimaflip",
        "fruit": {
            "@bowl": "bananas",
            "@protocol": "tcp"
        },
        "url": "https://this-is-a-sample/paramer?id=90"
    }
}

这是POST方法。

def post(self):
    f1=open("./log", 'w+')
    data = request.json
    if not data:
        # I know this is not equivalent to the JSON above. 
        # Just troubleshooting by dumping it all out.
        data = request.form
    print >>f1, data
    return ('', 201)

如果我使用带有application / json的cURL进行POST,那很好。我在request.data中正确获得了POSTed JSON。我将需要稍后将其渲染回JSON,但没有问题。

{
    u'alert': {
        u'@id': u'90'
        u'action': u'hoojimaflip', 
        u'fruit': {
              u'@bowl': u'bananas', 
              u'@protocol': u'tcp'
        },
        u'url': u'https://this-is-a-sample/paramer?id=90', 
    }
}

如果我使用application / x-www-form-urlencoded通过cURL发布,那么我应该能够在request.form中获取数据。但是,似乎某些事情正在破坏我的数据。

ImmutableMultiDict([('
   { "alert": { 
         "@id": "90",
         "action": "hoojimaflip",
         "fruit": {
             "@bowl": "bananas",
             "@protocol": "tcp"
         },
         "url": "https://this-is-a-sample/paramer?id', u'90"    
     }
 }'
 )])

“=”符号被用作某种记录分隔符并破坏了POSTed JSON。

有没有人有任何想法?我错过了一些明显的东西吗?

谢谢!

1 个答案:

答案 0 :(得分:2)

如果外部应用程序顽固地使用替代mime类型进行POST,您可以强制使用request.get_json() method来强制Flask将数据视为JSON ,设置{ {1}} force的参数:

True

不要试图将JSON有效负载视为表单数据,这将永远不会起作用。