Draco Malfago Draco Malfago - 1 year ago 174
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)
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:
however, trying this in the chrome console will not yield any output at all:

method: "POST",
url: "",
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 Source

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']
        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)
    return '''
    <title>This is just a testing template!</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

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

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

    url: "",
    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:

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download