Yiğit Güler
Yiğit Güler

Reputation: 1170

How to create URL Parameters from a list

I have a form with multiple select field. It is working through GET method. An example of request parameters generated by the form:

action=not-strummed&action=not-rewarded&keywords=test&page=2

Note that there is two "action" parameters. This is happening because of the multiple select.
What I want to do is:

The urllib.urlencode() isn't smart enough to generate url parameters from the list.

For example:

{
     "action": [u"not-strummed", u"not-rewarded"]
}

urllib.urlencode() transforms this dict as:

action=%5Bu%27not-strummed%27%2C+u%27not-rewarded%27%5D

This is completely wrong and useless.

That's why i wrote this iteration code to re-generate url parameters.

parameters_dict = dict(self.request.GET.iterlists())
parameters_dict.pop("page", None)
pagination_parameters = ""
for key, value_list in parameters_dict.iteritems():
    for value in value_list:
        pagination_item = "&%(key)s=%(value)s" % ({
            "key": key,
            "value": value,
        })
        pagination_parameters += pagination_item

It is working well. But it doesn't cover all possibilities and it is definitely not very pythonic.

Do you have a better (more pythonic) idea for creating url parameters from a list?

Thank you

Upvotes: 4

Views: 7390

Answers (1)

Taylan Pince
Taylan Pince

Reputation: 443

You should be able to use the second doseq parameter urlencode offers:

http://docs.python.org/2/library/urllib.html

So basically, you can pass a dictionary of lists to urlencode like so:

urllib.urlencode(params, True)

And it will do the right thing.

Upvotes: 15

Related Questions