Get data from ajax post in python file

I am trying to post some data using ajax post request and execute python file, extract data in python file and return result.

I have the following ajax code

        $(function () {
                    $("#upload").on("click", function (e) {
                        $.ajax({
                            type: 'post',
                            url: "test1.py",
                            data: {'param1':'abc'},
                            async: false,
                            success: function (response) {
                                console.log(response);
                            }
                        }).done(function (data) {
                            console.log(data);
                        });
                    });
                });

      

And the following python file

    #! /usr/bin/python
    from __future__ import print_function
    import cgi, cgitb
    def index():
        data = cgi.FieldStorage()
        mydata = data['param1'].value
        return return "test"

      

I am getting keyerror on param1 -> "KeyError: 'param1'". I also tried to use getValue (data ['param1']. This looks like a problem with passing data from the ajax call to the python file I want to execute ... But I can't figure out why.

Thank you in advance

+3


source to share


1 answer


I managed to find a solution. I hope other people can use it too.

The following python code I ran into to get postdata from an ajax call.



    def index(req):
        postData = req.form
        json = str(postData['param'].value)

      

+4


source







All Articles