Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse URL encoded data recieved via POST

I'm writing a django webhook for a service that send data via POST that is URL encoded. 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.

like image 491
hackerman Avatar asked Jul 09 '17 05:07

hackerman


People also ask

How do you make HTTP POST request with URL encoded body in flutter?

Response response = await http. post( url, body: "name=$name&surname=$firstName&mail=$mail&password=$password&birth=$birthDate&phone=$phone&confirmPassword=$confirmPassword", headers: { "Content-Type": "application/x-www-form-urlencoded" }, encoding: convert. Encoding. getByName("utf-8"), );

What are URL encoded requests?

URL encoding is a mechanism for translating unprintable or special characters to a universally accepted format by web servers and browsers.

What is URL encoded form data?

The application/x-www-form-urlencoded content type describes form data that is sent in a single block in the HTTP message body. Unlike the query part of the URL in a GET request, the length of the data is unrestricted.


1 Answers

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

like image 77
tosh Avatar answered Oct 13 '22 07:10

tosh