0

我尝试为我的资源实现 put 处理程序。这是代码:

class Settings(restful.Resource):
    def put(self):
        settings = request.form['settings']
        print settings

这是我将数据放在那里的方式:

import requests
url='http://localhost:8000/settings'
data = {'settings': {
            'record': {
                'b': 'ok',
                'c': 20,
                'd': 60,
            },
            'b': {
                'c': {
                    'd': 3,
                    'e': 2,
                    'f': 2,
                },
                'd': 5,
                'a': 'voice',
                'k': {
                    'l': 11.0,
                    'm': 23.0,
                },
            }
        }
}
requests.put(url, data)

当我这样做时,只会record在我的控制台中打印出来,所以当我进行验证时,它会失败,因为数据不是字典。我不知道出了什么问题。

它看起来与 Flask-RESTful Quickstart中的代码相同,如果我做对了,它requests可以与字典一起使用。

4

1 回答 1

2

When you pass in a dictionary as the data argument, requests encodes the data to ``application/x-www-form-urlencoded`, just like a browser form would. This encoding format does not support structured data beyond an (ordered, non-unique) key-value sequence.

Don't use application/x-www-form-urlencoded to post structured data. Use JSON instead:

import json

# ...

requests.put(url, json.dumps(data), headers={'Content-Type': 'application/json'})

Then in Flask use request.get_json() to load the payload again:

class Settings(restful.Resource):
    def put(self):
        settings = request.get_json()['settings']
        print settings

If you are using requests version 2.4.2 or newer, you can also leave the JSON encoding to the requests library; simply pass in the data object in as the json keyword argument; the correct Content-Type header will be set too:

requests.put(url, json=data)

Note that you then don't have to call json.dumps() yourself.

于 2014-07-08T14:28:39.413 回答