python - 如何使用 Flask 处理从 jquery 数据表发送的服务器端参数?

标签 python json flask jquery-datatables

当启用服务器端处理时,我在处理由 jquery datatables 1.10 发送的参数时遇到了一些问题。我像这样在 javascript 端初始化了数据表:

var table = $('#mytable').DataTable( {
                "processing": true,
                "serverSide": true,
                "ajax": {
                    'url': url,
                    'type': 'POST'
                },
                "columns": data
            } );

然后在基于 Flask 的服务器中接收 POST 请求:

@app.route('/data/<data_key>', methods=['POST'])
def get_data(data_key):
    print request.form

    # do some processing here in order to filter data
    # ...

    return Response(json.dumps(data), status=200, mimetype='application/json')

为了过滤数据,我尝试查看 request.form 内部,但结果很奇怪,无法轻松转换为对象数组。我得到这样的东西:

ImmutableMultiDict(
[
('columns[0][data]', u'ReportDate'), 
('draw', u'1'),
('columns[1][name]', u''), 
('columns[1][data]', u'FundName'),
('columns[0][orderable]', u'true'), 
('columns[1][searchable]', u'true'), 
('columns[1][orderable]', u'true'), 
('order[0][column]', u'0'), 
('columns[0][name]', u''), 
('order[0][dir]', u'asc'), 
('search[value]', u''), 
('columns[1][search][regex]', u'false'), 
('columns[0][search][value]', u''), 
('search[regex]', u'false'), 
('columns[1][search][value]', u''), 
('columns[0][search][regex]', u'false'), 
('start', u'0'), 
('length', u'10'), 
('columns[0][searchable]', u'true')
]
)

他们在 jquery 数据表文档中说:

The order[i] and columns[i] parameters that are sent to the server are arrays of information:

order[i] - is an array defining how many columns are being ordered upon - i.e. if the array length is 1, then a single column sort is being performed, otherwise a multi-column sort is being performed.

columns[i] - an array defining all columns in the table.

In both cases, i is an integer which will change to indicate the array value. In most modern server-side scripting environments this data will automatically be available to you as an array.

但是,Flask 将这些数据作为一个简单的字典提供,有没有办法轻松地将它转换为对象数组?

最佳答案

获取DataTable发送json

ajax: {
    url: "/api/data_table",
    type: "POST",
    data: function ( args ) {
      return { "args": JSON.stringify( args ) };
    }
},

在flask中,解析json

args = json.loads(request.values.get("args"))
columns = args.get("columns")

关于python - 如何使用 Flask 处理从 jquery 数据表发送的服务器端参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24890420/

相关文章:

python - 如果资源已经存在,我如何让 Django-Tastypie 覆盖它?

python - 有条件地将任意数量的默认命名参数传递给函数

json - Groovy比较两个具有未知节点名称和值的json

java - 验证字符串 JSON java 库与在线 - 不同的结果

postgresql - 在 Flask SqlAlchemy 查询中使用 to_char

python - 深度强化学习 - CartPole 问题

python - 如何使用 hinstance 确定 win32api.ShellExecute 是否成功?

json - hive中的多行JSON文件查询

html - 在同一文件中对大量相似的 HTML 元素使用分页?

python - Flask 测试 - 为什么覆盖范围不包括导入语句和装饰器?