How to create URL parameters from a list

I have a form with several selection fields. It works through the GET method. An example of request parameters generated by the form:

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

Note that there are two "action" parameters. This is due to multiple choice.
I want to do this:

  • Make parameter from parameters
  • Remove the page key from the dict file
  • Convert dict to parameter string

urllib.urlencode() not smart enough to generate URL parameters from a list.

For instance:

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

urllib.urlencode () converts this dict as:

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

This is completely wrong and useless.

This is why I wrote this iterative code to regenerate 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 works well. But it does not cover all the possibilities, and it is definitely not very pythons.

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

thanks

+4
source share
1 answer

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

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

So, basically, you can pass the list dictionary to urlencode like this:

 urllib.urlencode(params, True) 

And he will go right.

+12
source

Source: https://habr.com/ru/post/1492577/


All Articles