Search code examples
pythonarraysjsonangularjscherrypy

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


I need to pass from AngularJS to python a JSON object. JSON structure would be:

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

This is a fragment of my AngularJS controller. All parameters are input from an HTML form (in this case the array "cars" has been created manually, to show you the way I have it programmed)

$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'}
    });
    ...
}

If I inspect the POST request I see the following parameters:

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

Initially, I will not know how many items will have the array "cars". Now, this is the header of a python function. I know how to store the normal arguments but I don't know how to do the same thing with array "cars". I would store it as a python list or dictionary.

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

How can I store the array?


Solution

  • I won't tell you about AngularJS part as it's out of my interest, but I can tell you about CherryPy. It is be much easier for you to send and process your data as application/json, so I suggest you to avoid application/x-www-form-urlencoded and search how to send JSON with your client library. With CherryPy, of course, you can handle both ways.

    #!/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)