Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a javascript array to a python script using flask [using flask example]

I am trying to get the flask/jquery/ajax example working for my specific case, but I am coming up short every time. I am aware this sort of question has been asked several times, but the answers do not help me (Yes, I am new to this).

The example passes a string from javascript to python. I would like to pass an array over. The web suggests that this is possible. Here is what I have:

HTML/Flask Template:

{% extends "layout.html" %}
{% block title %}Test{% endblock %}
{% block content %}
    <div>
      <h1>Flask Jquery Test</h1>
      <div>
        <input type="button" value="Transfer" id="button" />
      </div>
      <div>
        Wordlist<br />
        <select multiple="multiple" id="wordlist" size="5">
            <option>Volvo</option>
            <option>Audi</option>
            <option>BMW</option>
            <option>Mercedes</option>
            <option>Toyota</option>
        </select>
        <span id="result"></span>
      </div>
    </div>
{% endblock %}

JS Script:

$(document).ready(function() {
    $("#button").bind('click', function(){
        //Get all words from list
        var list = [];
        $("#wordlist option").each(function(){
            list.push($(this).val());
        });
        //var list = $( "#wordlist option" ).val();
        console.log(list);
        $.getJSON($SCRIPT_ROOT + '/_array2python', {
            wordlist: list.toString()
        }, function(data){
            console.log(data.result)
            $( "#result" ).text(data.result);
        });
        return false;
    });
});

Python:

@app.route('/')
def start_page():
    return render_template('index.html')

@app.route('/_array2python')
def array2python():
    wordlist = request.args.get('wordlist', [])
    return jsonify(result=wordlist)

@app.errorhandler(404)
def page_not_found(e):
    """Return a custom 404 error."""
    return 'Sorry, nothing at this URL.', 404

Now, when passing into the list variable a string (e.g. var list = $( "#wordlist option" ).val(); ), this code works just fine. However, when trying it with an array, it only ever passes the backup value (i.e. []).

Does this mean, I can only pass strings to python? How would I best pass a javascript array to python?

Thanks everyone for your help!

P.S. Maybe it is important to mention. I am using google app engine to host this code.

=================================================================================

FYI, these are the SO sites that I tried to follow and they did not help me:

Passing Javascript Array to Flask (Excellent and very detailed answer, but can't get it to work)

Passing data from javascript into Flask

Return data from html/js to python

like image 975
Nebelhom Avatar asked May 30 '14 07:05

Nebelhom


1 Answers

Here is another way to pass JS Array to python :

JS Side:

$.getJSON($SCRIPT_ROOT + '/_array2python', {
        wordlist: JSON.stringify(list)
    }, function(data){
        console.log(data.result)
        $( "#result" ).text(data.result);
    });

Python Side:

import json

@app.route('/_array2python')
def array2python():
    wordlist = json.loads(request.args.get('wordlist'))
    # do some stuff
    return jsonify(result=wordlist)

As far as I know, strings are the only way to pass array from client to server.

like image 100
Thomas N. Avatar answered Sep 22 '22 13:09

Thomas N.