如何从 AngularJS 向上传递数组 python 并存储?

How to pass an array from AngularJS up python and store?

我需要从AngularJS传到python一个JSONobject。 JSON 结构为:

{ "name": "Bob",
  "address": "Springfield",
  "cars": [
    { "model": "Renault C15", "year": "1965" },
    ...
    { "model": "Ford Ka", "year": "1998" } ]
}

这是我的 AngularJS 控制器的片段。所有参数都是从 HTML 表单输入的(在这种情况下,数组 "cars" 是手动创建的,以向您展示我的编程方式)

$scope.cars= [];
var car1 = { model: 'Renault C15', year: '1965' };
var car2 = { model: 'Ford Ka', year: '1998' };
$scope.cars.push(car1);
$scope.cars.push(car2);
...
$scope.newForm = function() {
    var dataToSend= {
        name: $scope.name,
        address: $scope.address,
        cars: $scope.cars
    };
    $http({
        method: 'POST',
        url: '/myUrl/something',
        data: $.param(dataToSend),
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    });
    ...
}

如果我检查 POST 请求,我会看到以下参数:

name Bob
address Springfield
cars[0][model]  Renault C15
cars[0][year]   1965
cars[1][model]  Ford Ka
cars[1][year]   1998

最初,我不知道数组 "cars" 中会有多少项。 现在,这是 python 函数的 header。我知道如何存储普通参数,但我不知道如何用数组 "cars" 做同样的事情。我会将其存储为 python 列表或字典。

def something(self, **params):
    ...
    name=params['name']
    address=params['address']
    ...

如何存储数组?

我不会告诉您有关 AngularJS 的部分,因为这不符合我的兴趣,但我可以告诉您有关 CherryPy 的信息。作为 application/json 发送和处理数据对您来说要容易得多,因此我建议您避免使用 application/x-www-form-urlencoded 并搜索如何使用您的客户端库发送 JSON。当然,使用 CherryPy,您可以同时处理这两种方式。

#!/usr/bin/env python
# -*- coding: utf-8 -*-


import cherrypy


config = {
  'global' : {
    'server.socket_host' : '127.0.0.1',
    'server.socket_port' : 8080,
    'server.thread_pool' : 8
  }
}

class App:

  @cherrypy.expose
  def index(self):
    return '''<!DOCTYPE html>
      <html>
      <head>
        <title>CherryPy demo</title>
        <script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>
        <script type='text/javascript'>
          var data = { 
            "name": "Bob",
            "address": "Springfield",
            "cars": [
              { "model": "Renault C15", "year": "1965" },
              { "model": "Ford Ka", "year": "1998" }
            ]
          };

          $(document).ready(function()
          {
            $('#send-json').on('click', function()
            {
              $.ajax({
                'type'        : 'POST',
                'dataType'    : 'JSON',
                'contentType' : 'application/json',
                'url'         : '/jsonin',
                'data'        : JSON.stringify(data),
                'success'     : function(response)
                {
                  console.log(response);  
                }
              });
            });
            $('#send-form').on('click', function()
            {
              $.ajax({
                'type'        : 'POST',
                'dataType'    : 'JSON',
                'url'         : '/formin',
                'data'        : data,
                'success'     : function(response)
                {
                  console.log(response);  
                }
              });
            });            
          });
        </script>
      </head>
      <body>
        <p><a href='#' id='send-json'>Send JSON</a></p>
        <p><a href='#' id='send-form'>Send form</a></p>
      </body>
      </html>
    '''

  @cherrypy.expose
  @cherrypy.tools.json_out()
  def formin(self, **kwargs):
    # You can just print a variable a see it in the terminal
    # where CherryPy is executed
    print(kwargs)
    # You would see
    # {
    #   'cars[1][year]': u'1998', 
    #   'name': u'Bob', 
    #   'cars[0][model]': u'Renault C15', 
    #   'address': u'Springfield', 
    #   'cars[0][year]': u'1965', 
    #   'cars[1][model]': u'Ford Ka'
    # }
    return kwargs.items()

  @cherrypy.expose
  @cherrypy.tools.json_in()
  @cherrypy.tools.json_out()
  def jsonin(self):
    data = cherrypy.request.json # just the same structure
    return data.items()


if __name__ == '__main__':
  cherrypy.quickstart(App(), '/', config)