How to parse application/x-www-form-urlencoded rec

2020-07-06 08:49发布

问题:

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

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.

回答1:

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']}

Both python 2/3:

>>> from six.moves.urllib.parse import parse_qs

UPD

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')]

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).