Search code examples
pythonpython-3.xwsgiurllibpython-3.2

How to parse empty value of parameter in HTTP request in python?


I parse the following request param1=value1&param2=&param3=value3 using urllib.parse.parse_qs (python 3 wsgi application) but this function returns a dict with only param1 and param3 keys. What function can I use to get also the empty param2?


Solution

  • It's right there in the documentation for parse_qs():

    The optional argument keep_blank_values is a flag indicating whether blank values in percent-encoded queries should be treated as blank strings. A true value indicates that blanks should be retained as blank strings. The default false value indicates that blank values are to be ignored and treated as if they were not included.

    In other words, instead of

    >>> parse_qs(querystring)
    {'param1': ['value1'], 'param3': ['value3']}
    

    ... you need:

    >>> parse_qs(querystring, keep_blank_values=True)
    {'param2': [''], 'param1': ['value1'], 'param3': ['value3']}