我从 HTML 表单发送数据,我用 python( Pyramid 框架)处理它,这就是我的看法:
@view_config(renderer='json', request_method='POST')
def modify(self):
d = self.request.params
if d.get("perms"):
if type(d.get("perms")) == str or type(d.get("perms")) == unicode:
d["perms"] = [d["perms"]]
for perm in d["perms"]:
d[perm] = "on"
当我尝试执行 d["perms"] = [d["perms"]]
时,出现错误:
KeyError: 'NestedMultiDict objects are read-only'
我试图将上面的代码更改为:
perms = []
for k, v in d.iteritems():
if k == "perms":
if type(v) == str or type(v) == unicode:
perms = [v]
for perm in perms:
d[perm] = "on"
但它给了我同样的错误。
是否可以将 MultiDict
值添加到列表中?
如果是这样,如何?
为什么 MultiDict
是只读的?
最佳答案
你不需要做你正在做的事 :) 只需使用 request.getall('perm')
,它总是会返回一个列表。
Several attributes of a WebOb request are “multidict”; structures (such as request.GET, request.POST, and request.params). A multidict is a dictionary where a key can have multiple values. The quintessential example is a query string like ?pref=red&pref=blue; the pref variable has two values: red and blue.
In a multidict, when you do request.GET['pref'] you’ll get back only 'blue' (the last value of pref). Sometimes returning a string, and sometimes returning a list, is the cause of frequent exceptions. If you want all the values back, use request.GET.getall('pref'). If you want to be sure there is one and only one value, use request.GET.getone('pref'), which will raise an exception if there is zero or more than one value for pref.
http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/webob.html
(您也不应尝试修改 request.params
的值,它是只读的。请改用单独的字典。)
关于python - 将 multidict 值添加到列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22638401/