Google App Engine: Python: WebOb: How to get POST

2019-07-18 05:38发布

I am building a web app on the Google App Engine platform, which uses webapp2, which uses WebOb. I would like to POST some data in JSON format, including nested arrays and dictionaries. E.g.:

$.post('/addvendor', {'vendor': {'name': 'test', 'description': 'a good company', 'tags':['foo', 'bar']}}, function(data){console.log(data)}, 'application/json')

However, on the server side, the data comes in as a flat "MultiDict" object, not anything like the original nested JSON object that I POSTed. E.g.:

>>> print self.request.params.items()
[(u'vendor[name]', u'test'), (u'vendor[description]', u'a good company'), (u'vendor[tags][]', u'foo'), (u'vendor[tags][]', u'bar')]

This object is very difficult to parse. In my server code, is there a way to get the same data in standard JSON format, or at least a Python equivalent using nested dictionaries and arrays, on the server so that I can manipulate and examine the data easily?

2条回答
我命由我不由天
2楼-- · 2019-07-18 06:27

use json.dumps(yourdata) don't forgot to change the header Content-Type to application/json

headers = {
"Content-Type": "application/json"
}
session.post(<url>, data=json.dumps(yourdata))
查看更多
来,给爷笑一个
3楼-- · 2019-07-18 06:36

(updated with jayhendren's help) You should use $.ajax and manually set contentType='application/json; charset=utf-8' instead because $.post uses default "application/x-www-form-urlencoded;" content type. Also you need to manually encode data to JSON-string with JSON.stringify:

$.ajax({url:'/addvendor', 
        type: 'post', 
        data:JSON.stringify({'vendor': {'name': 'test', 'description': 'a good company', 'tags':['foo', 'bar']}}), 
        contentType:'application/json; charset=utf-8',
        dataType: "json",
        success:function(data){console.log(data)}})

...

print json.loads(self.request.body)
查看更多
登录 后发表回答