Question

I am sending data from an HTML form, and I handle it with python(Pyramid framework), this is what I have in my view:

 @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"

When I try to do d["perms"] = [d["perms"]], I get an error:

KeyError: 'NestedMultiDict objects are read-only'

I have tried to change the above piece of code to:

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"

But it gives me the same error.

Is it possible to add a MultiDict value to a list? If so, how? Why is a MultiDict read-only?

Was it helpful?

Solution

You don't need to do what you're doing :) Just use request.getall('perm'), which will always return a list.

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

(you should also not try to modify the values of request.params, which is read-only. Use a separate dict instead.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top