Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • Make a dict from parameters
  • Remove "page" key from the dict
  • Transform-back the dict into the parameter string

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

like image 460
Yiğit Güler Avatar asked Dec 09 '22 14:12

Yiğit Güler


1 Answers

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.

like image 145
Taylan Pince Avatar answered Dec 11 '22 09:12

Taylan Pince