简体   繁体   中英

Sending json data through curl/urllib2 to Pyramid application does not give a proper request.POST

I'm currently testing out creating a RESTful json API, and in the process I've been testing out posting data via curl primarily to see if I can login through a request. I can't figure out what to do even if I hack it to work, but that's a separate question.

I'm sending the following POST request to my app:

curl -X POST http://localhost:6543/users/signin -d '{"username":"a@a.com","password":"password"}' 

And when I see what data is in my request, the output is extremely strange:

ipdb> self.request.POST
MultiDict([('{"username":"a@a.com","password":"password"}', '******')])
ipdb> self.request.POST.keys()
['{"username":"a@a.com","password":"password"}']
ipdb> self.request.POST.values()
[u'']

So, it comes out to be a MultiDict with my json object as a string key, and a blank string as its value?! That doesn't seem right.

Removing the single quotes in my json declaration gives the following:

ipdb> self.request.POST
MultiDict([('username:a@a.com', u'')])

Does anyone have any idea why my data may not be being posted correctly?

Update:

To be clear, the header I'm using is in fact application/x-www-form-urlencoded.

ipdb> self.request.headers['CONTENT-TYPE']
'application/x-www-form-urlencoded'

What I DID find is that for some reason using the requests library works when I do the following:

In [49]: s.post('http://localhost:6543/users/signin', data=[('username', 'a@a.com'), ('password', 'password')], headers={'content-type': 'application/x-www-form-urlencoded'})
Out[49]: <Response [200]>

The fact that it doesn't work with curl as expected is still troubling though.

I'm not sure which content type you are attempting to upload - application/json or application/x-www-form-urlencoded. request.POST only works with the latter option, and request.json_body is used to parse data from a json request body.

To be clear, application/x-www-form-urlencoded is the format used when your web browser submits a form. It's a key/value format looking like a=b&c=d&e=f . From there you can expect request.POST to contain a dictionary with the keys a , c , and e .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM