问题描述
我正在为服务编写django webhook,该服务通过POST
以我认为的application/x-www-form-urlencoded
格式发送数据.示例POST
显示如下:
I'm writing a django webhook for a service that send data via POST
in what I believe is the application/x-www-form-urlencoded
format. Example POST
show below:
POST id=a5f3ca18-2935-11e7-ad46-08002720e7b4
&originator=1123456789
&recipient=1987654321
&subject=MMS+reply
&body=View+our+logo
&mediaUrls[0]=https://storage.googleapis.com/mms-assets/20170424/a0b40b77-30f8-4603-adf1-00be9321885b-messagebird.png
&mediaContentTypes[0]=image/png
&createdDatetime=2017-04-24T20:15:30+00:00
我了解如何解析json
,但是我之前从未遇到过这种格式.关于如何通过POST
处理此问题,似乎没有任何有用的教程.我目前仍处于停滞状态,因此将不胜感激.
I understand how to parse json
but I haven't encountered this format before. There doesn't appear to be any useful tutorials for how to handle this via POST
. I'm stuck at this point so help would be greatly appreciated.
推荐答案
Python 2:
>>> from urlparse import parse_qs
>>> parse_qs('foo=spam&bar=answer&bar=42')
{'foo': ['spam'], 'bar': ['answer', '42']}
Python 3:
>>> from urllib.parse import parse_qs
>>> parse_qs('foo=spam&bar=answer&bar=42')
{'foo': ['spam'], 'bar': ['answer', '42']}
两个python 2/3:
Both python 2/3:
>>> from six.moves.urllib.parse import parse_qs
UPD
还有parse_qsl
函数,该函数返回两个项目元组的列表,例如
There is also parse_qsl
function that returns a list of two-items tuples, like
>>> parse_qsl('foo=spam&bar=answer&bar=42')
[('foo', 'spam'), ('bar', 'answer'), ('bar', '42')]
非常适合将此类列表传递给dict()
构造函数,这意味着您获得的dict每个名称仅包含一个值.请注意,姓氏/值对优先于同名的早期出现(请参见 dict (在库参考中).
It is very suitable to passing such list to dict()
constructor, meaning that you got a dict with only one value per name. Note that the last name/value pair takes precedence over early occurrences of same name (see dict in library reference).
这篇关于如何解析通过POST收到的application/x-www-form-urlencoded的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!