Draco Malfago Draco Malfago - 3 months ago 16
Ajax Question

running a python script within Flask

So I have this simple python script running on Flask that I'd like to pass variables to with an ajax jQuery request. I might be missing something obvious but I can't get it to work properly.

@app.route('/test', methods=['GET', 'POST'])
def test():
my_int1 = request.args.get('a')
my_int2 = request.args.get('b')
my_list = [my_int1, my_int2]
with open('my_csv.csv', 'wb') as myfile:
wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
wr.writerow(my_list)
return '' #does one have to have an return even tho it is just a script?


So, above will work fine when just passing parameters to the URL field:
http://127.0.0.1:5000/test?a=10&b=25
however, trying this in the chrome console will not yield any output at all:

$.ajax({
method: "POST",
url: "127.0.0.1:5000/test",
data: {a: 10, b: 25},
dataType: "script"
});


What am I missing and why does the above jquery ajax request not work?
$.ajax is not a function(…)

Answer

Please, try with the following code and let me know if that's what you are looking for:

from flask import Flask, request
import csv

app = Flask(__name__)


@app.route('/test', methods=['GET', 'POST'])
def test():
    if request.is_xhr:
        a = request.json['a']
        b = request.json['b']
    else:
        a = request.args.get('a')
        b = request.args.get('b')
    my_list = [a, b]
    with open('my_csv.csv', 'wb') as myfile:
        wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
        wr.writerow(my_list)
    return '''
<html>
  <head>
    <title>This is just a testing template!</title>
  </head>
  <body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  </body>
</html>
'''


if __name__ == "__main__":
    app.run(host='0.0.0.0', debug=True)

To test from your Chrome console, you need first to go to http://127.0.0.1:5000/test (after that, jQuery will be available in your browser) then you run the following code:

$.ajax({
    url: "http://127.0.0.1:5000/test",
    method: "POST",
    headers: {'Content-Type':'application/json'},
    data: JSON.stringify({a: 10, b: 25}),
    success: function(data){console.log('result: ' + data);}
});

If you have a Cross-origin issue, add also the below code to your app.py file:

@app.after_request
def after_request(response):
    response.headers.add('Access-Control-Allow-Origin', '*')
    response.headers.add('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
    response.headers.add('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE, OPTIONS')
    return response