5

A while ago, I had noticed that when encoding a map name: value to 'application/x-www-form-urlencoded, it renders something like that (here I use Python):

>>> from urllib import urlencode
>>> urlencode({'hello': '', 'blabla': 'hihi'})
'blabla=hihi&hello='

But the parsing (at least with Python), just strips the pairs that have an empty value :

>>> from urlparse import parse_qs
>>> parse_qs('blabla=hihi&hello=')
{'blabla': ['hihi']}

So ... is it the standard behaviour ? Where can I find the reference on how www-form-urlencoded should be parsed ? I have googled a while, found the RFCs for uris, W3c docs for forms, and so on but nothing about how the empty values should be treated. Can somebody give me a pointer to that ???

sebpiq
  • 7,540
  • 9
  • 52
  • 69

1 Answers1

4

As far as I know, there is no "standard" for this. The only thing that is described (in the html spec, as you have found out), is how a browser should encode form data. What you want to do (or not) with empty values is up to you.

Note that urlparse.parse_qs() has an optional parameter, keep_blank_values that allows you to control how it should handle those:

>>> from urlparse import parse_qs
>>> parse_qs('blabla=hihi&hello=', keep_blank_values=True)
{'blabla': ['hihi'], 'hello': ['']}
Steven
  • 28,002
  • 5
  • 61
  • 51
  • Thanks for the answer !! I didn't know this "keep_blank_values" kwarg. Do you know - by any chance - if there is a setting in Django for that ? – sebpiq Mar 08 '11 at 10:27
  • Doestn't Django already do it that way for `request.GET` and `request.POST`? – Steven Mar 08 '11 at 11:01
  • @Steven : well ... I don't believe so, but I might be wrong ... though I am pretty sure it doesn't – sebpiq Mar 08 '11 at 11:52
  • I'm not using django myself, so I'm not sure, but these SO questions seem to indicate it does: http://stackoverflow.com/questions/3500859/django-request-get and http://stackoverflow.com/questions/2422055/how-to-check-if-request-get-var-is-none – Steven Mar 08 '11 at 15:53
  • @Steven : Ok ... my mistake you were right, I also checked with Django, and indeed the parameters are not stripped. However, the thing that got me started with that is that with 'select multiple', if nothing is selected, the parameter is not sent. However that's a problem of the client rather than the server. – sebpiq Mar 09 '11 at 07:57
  • I posted a new question (the "real" question for me actually) here : http://stackoverflow.com/questions/5242944/is-there-a-standard-client-behaviour-for-submitting-an-empty-select-multiple – sebpiq Mar 09 '11 at 08:09