python - 将 multidict 值添加到列表

标签 python list dictionary pyramid

我从 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/

相关文章:

python - 无法使用 Rapids.ai 版本 21.08 将 cudf、cupy 和 cuml 安装到 colab 中

python - 计算自上次维护以来的日期差异的有效方法是什么?

python - 是否存在生成器装饰器?

list - Flutter 上传列表到 Google Firestore

java.lang.ClassCastException : [Ljava. lang.Object;不能转换为 [Ljava.lang.String;

python - 如何使用字典来翻译/替换数组的元素?

python - 提取字符串的一部分

c# - Razor @foreach 列表问题

c# - 在 WPF 应用程序中动态创建按钮列表

javascript - 在 Javascript (node js) 中将带有 & 符号的字符串转换为键值映射