How to parse URL encoded data recieved via POST

后端 未结 1 838
不知归路
不知归路 2021-01-04 11:35

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-2         


        
相关标签:
1条回答
  • 2021-01-04 12:05

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

    0 讨论(0)
提交回复
热议问题