Question

So unfortunately I find myself in the situation where I need to modify an existing Pylons application to handle URLs that provide multiple parameters with the same name. Something like the following... domain:port/action?c=1&v=3&c=4

Conventionally the parameters are accessed this way...

from pylons import request
c = request.params.get("c")
#or
c = request.params["c"]

This will return "4" as the value in either case, because ignoring all but the last value seems to be the standard behavior in these situations. What I really need though, is to be able to access both. I tried printing out request.params and get something like this...

NestedMultiDict([(u'c', u'1'),(u'v', u'3'),(u'c', u'4')])

I haven't found a way to index into it, or access that first value for c.

I found a similar question relating to this problem, but solved with PHP:

Something along these lines would work well for me, but maybe some Python code that would fit into Pylons. Has anyone dealt with something like this before?

Était-ce utile?

La solution

From the docs - http://docs.pylonsproject.org/projects/pyramid/en/1.3-branch/glossary.html#term-multidict :

multidict An ordered dictionary that can have multiple values for each key. Adds the methods getall, getone, mixed, add and dict_of_lists to the normal dictionary interface. See Multidict and pyramid.interfaces.IMultiDict.

So just call:

request.params.getall('c')

Autres conseils

As an exercise, a rendering in Python of the PHP in the other question (also includes a dummy parameter to illustrate the need for url decoding):

from urlparse import urlparse
from urllib import unquote

url = 'http://www.example.com/action?c=1&v=3&c=4&d=%3A%24%23%40%3D%3F%25%5EQ%5E%24'

url = urlparse(url)

params = url.query.split('&')
params = [ tuple(p.split('=')) for p in params ]
params = [ [unquote(p[0]), unquote(p[1])] for p in params ]

print params

# [['c', '1'], ['v', '3'], ['c', '4'], ['d', ':$#@=?%^Q^$']]
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top