Using data from Ajax in python script

I am trying to use a Python script to populate a PostgreSQL table with data received from an AJAX POST.

My Ajax command:

function ajaxFct() {
    $.ajax({
        async: true,
        type: "POST",
        url: "/myDir/cgi-bin/send_array.py",
        data: my_array,
        dataType: "html",
        success : function(data) {
            document.getElementById("ajaxAnchor").innerHTML = "Exported something to DB table" 
        }
    });  
}

      

my_array looks like a csv string with multiple lines like:

["header1, header2, header3", "some_value, 45.99, text"]

I just can't figure out how to simply use this array in my python script (send_array.py)

The script currently works fine with some local data (see the second cursor.execute command):

import psycopg2
import psycopg2.extras
import cgitb

def main():
    cgitb.enable()

    conn_string = "host='...' dbname='...' user='...' password='...' port=..."
    conn = psycopg2.connect(conn_string)
    cursor = conn.cursor()    

    cursor.execute("DROP TABLE IF EXISTS myDb.myTable; CREATE TABLE myDb.myTable(id serial PRIMARY KEY, header1 varchar, header2 decimal, header3 varchar);")
    cursor.execute("INSERT INTO myDb.myTable (header1, header2, header3) VALUES (%s, %s, %s)", ("local_test1",0.12345,"local_test2"))

    # Make the changes to the database persistent
    conn.commit()    

    cursor.close()
    conn.close()

if __name__ == "__main__":
    main()

      

So my question is basically:

How do I access the data sent from the AJAX POST, i.e. the my_array to be used in the SQL query instead of locally defined data?

Thanks for any help, I am still new to this and I am having a hard time finding an answer on the internet.

0


source to share


1 answer


I finally found a way to get data from an Ajax command in a Python script. First, I had to format the data sent by the browser:

data: JSON.stringify(myArray),

      



Then I used sys.stdin in the following command in a python script to store the sent data in a local variable:

myDataInPython = json.load(sys.stdin)

      

0


source







All Articles