Reputation: 32220
Following is the code block that is working as expected.
for key in context:
if isinstance(context[key],collections.Iterable):
queryString += '%s=%s&' % (key, urllib.quote(context[key]))
else:
queryString += '%s=%s&' % (key, context[key])
return queryString
But I did not understand the use of if block. Shouldn't the following work?
for key in context:
queryString += '%s=%s&' % (key, context[key])
return queryString
Upvotes: 1
Views: 68
Reputation: 92657
It is basically saying "quote anything that isn't numeric or a sequence when converting to a string representation". It escapes characters to make them urlencoded.
The if
will prevent it from quoting int
, float
, etc, because those would crash the quote
function.
context = {'a': 'a b c', 'b': ('a', '@', 'c'), 'c': 1}
queryString = ''
for key in context:
if isinstance(context[key],collections.Iterable):
queryString += '%s=%s&' % (key, urllib.quote(context[key]))
else:
queryString += '%s=%s&' % (key, context[key])
print queryString
# a=a%20b%20c&c=1&b=a%40c&
Though it only makes sense depending on what your potential inputs could be (the value of context). It would crash on say, a list of ints.
Not using quote
would look like this:
for key in context:
queryString += '%s=%s&' % (key, context[key])
# invalid url format
# a=a b c&c=1&b=('a', '@', 'c')&
And running the quote
on everything would result in:
for key in context:
queryString += '%s=%s&' % (key, urllib.quote(context[key]))
...
TypeError: argument 2 to map() must support iteration
Upvotes: 3