Converting request params from DataTables with Pyramid

369 views Asked by At

I'm using Pyramid to handle ajax requests from DataTable. The request params have keys that are passed in like this:

'columns[0][search]', 'columns[1][search]', 'columns[0][data]', 'columns[0][data]'

Is there a way to tell pyramid (or another python library) to parse these request params into a nested dict so it looks more like:

{'columns': {
    '0': {'search': X, 'data': X}, 
    '1': {'search': X, 'data': X},
}}
1

There are 1 answers

3
Brendan Abel On BEST ANSWER

This works. It would be nice if I could return it as a set of nested MultiDicts so I could continue to use the getone() and getall() methods, but I don't seem to be able to instantiate the MultiDicts from pyramid.

def unflatten_multidict(multidict):
    d = {}
    for k in multidict.keys():
        m = re.match(r'^([^\[\]]+)((?:\[[^\[\]]+\])+)', k)
        if m:
            attr = m.group(1)
            lastd = d.setdefault(attr, {})
            subkeys = re.findall(r'\[([^\[\]]+)\]', m.group(2))
            for i, subkey in enumerate(subkeys):
                if i < len(subkeys) - 1:
                    lastd = lastd.setdefault(subkey, {})
                else:
                    lastd[subkey] = multidict.get(k)
        else:
            d[k] = multidict.get(k)

    return d