running a python script within Flask
<p>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. </p>

<pre><code>@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?
</code></pre>

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

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

<p>What am I missing and why does the above jquery ajax request not work? <code>$.ajax is not a function(â¦)</code></p>

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

<pre><code>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 '''
&lt;html&gt;
  &lt;head&gt;
    &lt;title&gt;This is just a testing template!&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"&gt;&lt;/script&gt;
  &lt;/body&gt;
&lt;/html&gt;
'''


if __name__ == "__main__":
    app.run(host='0.0.0.0', debug=True)
</code></pre>

<p>To test from your Chrome console, you need first to go to <strong><a href="http://127.0.0.1:5000/test" rel="nofollow">http://127.0.0.1:5000/test</a></strong> (after that, jQuery will be available in your browser) then you run the following code:</p>

<pre><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);}
});
</code></pre>

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

<pre><code>@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
</code></pre>

jquery python ajax flask