How to get multiple parameters with same name from a URL in Pylons?

一笑奈何 提交于 2019-12-08 18:39:46

问题


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?


回答1:


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')



回答2:


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^$']]


来源:https://stackoverflow.com/questions/14734750/how-to-get-multiple-parameters-with-same-name-from-a-url-in-pylons

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!