如何解码 python flask 中的 dataTables Editor 表单?

How to decode dataTables Editor form in python flask?

我有一个 Flask 应用程序正在接收来自数据表编辑器的请求。在服务器收到后,request.form 看起来像(例如)

ImmutableMultiDict([('data[59282][gender]', u'M'), ('data[59282][hometown]', u''), 
('data[59282][disposition]', u''), ('data[59282][id]', u'59282'),
('data[59282][resultname]', u'Joe Doe'), ('data[59282][confirm]', 'true'), 
('data[59282][age]', u'27'), ('data[59282][place]', u'3'), ('action', u'remove'), 
('data[59282][runnerid]', u''), ('data[59282][time]', u'29:49'),
('data[59282][club]', u'')])

我正在考虑使用类似于这个非常难看的代码的东西来解码它。有没有更好的方法?

from collections import defaultdict

# request.form comes in multidict [('data[id][field]',value), ...]
# so we need to exec this string to turn into python data structure
data = defaultdict(lambda: {})   # default is empty dict

# need to define text for each field to be received in data[id][field]
age = 'age'
club = 'club'
confirm = 'confirm'
disposition = 'disposition'
gender = 'gender'
hometown = 'hometown'
id = 'id'
place = 'place'
resultname = 'resultname'
runnerid = 'runnerid'
time = 'time'

# fill in data[id][field] = value
for formkey in request.form.keys():
    exec '{} = {}'.format(d,repr(request.form[formkey]))

我决定采用一种比使用 exec 更安全的方法:

from collections import defaultdict

def get_request_data(form):
    '''
    return dict list with data from request.form

    :param form: MultiDict from `request.form`
    :rtype: {id1: {field1:val1, ...}, ...} [fieldn and valn are strings]
    '''

    # request.form comes in multidict [('data[id][field]',value), ...]

    # fill in id field automatically
    data = defaultdict(lambda: {})

    # fill in data[id][field] = value
    for formkey in form.keys():
        if formkey == 'action': continue
        datapart,idpart,fieldpart = formkey.split('[')
        if datapart != 'data': raise ParameterError, "invalid input in request: {}".format(formkey)

        idvalue = int(idpart[0:-1])
        fieldname = fieldpart[0:-1]

        data[idvalue][fieldname] = form[formkey]

    # return decoded result
    return data

这个问题有一个公认的答案并且有点旧,但是由于 DataTable 模块似乎在 jQuery 社区中仍然很受欢迎,我相信这种方法可能对其他人有用。我刚刚写了一个基于正则表达式和 dpath module 的简单解析函数,尽管它看起来不是很可靠的模块。由于 exception-relied 片段,该片段可能不是很简单,但这只是防止 dpath 尝试将字符串解析为我发现的整数索引的一种方法。

import re, dpath.util

rxsKey = r'(?P<key>[^\W\[\]]+)'
rxsEntry = r'(?P<primaryKey>[^\W]+)(?P<secondaryKeys>(\[' \
         + rxsKey \
         + r'\])*)\W*'

rxKey = re.compile(rxsKey)
rxEntry = re.compile(rxsEntry)

def form2dict( frmDct ):
    res = {}
    for k, v in frmDct.iteritems():
        m = rxEntry.match( k )
        if not m: continue
        mdct = m.groupdict()
        if not 'secondaryKeys' in mdct.keys():
            res[mdct['primaryKey']] = v
        else:
            fullPath = [mdct['primaryKey']]
            for sk in re.finditer( rxKey, mdct['secondaryKeys'] ):
                k = sk.groupdict()['key']
                try:
                    dpath.util.get(res, fullPath)
                except KeyError:
                    dpath.util.new(res, fullPath, [] if k.isdigit() else {})
                fullPath.append(int(k) if k.isdigit() else k)
            dpath.util.new(res, fullPath, v)
    return res

实际使用基于原生flaskrequest.form.to_dict()方法:

    # ... somewhere in a view code
    pars = form2dict(request.form.to_dict())

正如预期的那样,输出结构包括字典和列表。例如:

# A little test:
rs = jQDT_form2dict( {
        'columns[2][search][regex]' : False,
        'columns[2][search][value]' : None,
        'columns[2][search][regex]' : False,
    } )

生成:

{
    "columns": [
        null, 
        null, 
        {
            "search": {
                "regex": false, 
                "value": null
            }
        }
    ]
}

Update:将列表作为字典处理(以更有效的方式),可以在 if 子句的 else 部分使用以下块简化此代码段:

    # ...
    else:
        fullPathStr = mdct['primaryKey']
        for sk in re.finditer( rxKey, mdct['secondaryKeys'] ):
            fullPathStr += '/' + sk.groupdict()['key']
        dpath.util.new(res, fullPathStr, v)