在Flask中运行python脚本

时间:2016-09-02 17:54:44

标签: jquery python ajax flask

所以我在Flask上运行这个简单的python脚本,我想用ajax jQuery请求传递变量。我可能会遗漏一些明显但我无法正常工作的东西。

@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?

因此,只需将参数传递给URL字段时,上面的工作正常:http://127.0.0.1:5000/test?a=10&b=25但是,在chrome控制台中尝试这一点根本不会产生任何输出:

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

我错过了什么,为什么上面的jquery ajax请求不起作用? $.ajax is not a function(…)

3 个答案:

答案 0 :(得分:1)

请参阅http://flask.pocoo.org/docs/0.11/api/#flask.Request

request.args : If you want the parameters in the URL
request.form : If you want the information in the body (as sent by a html POST form)
request.values : If you want both

试试这个

@app.route('/test', methods=['GET', 'POST'])
def test():
    my_int1 = request.values.get('a')
    my_int2 = request.values.get('b')

答案 1 :(得分:1)

请尝试使用以下代码,如果您正在寻找,请告诉我们:

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)

要从Chrome控制台进行测试,首先需要转到 http://127.0.0.1:5000/test (之后,jQuery将在您的浏览器中显示),然后运行以下代码:

$.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);}
});

如果您遇到跨域问题,请在 app.py 文件中添加以下代码:

@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

答案 2 :(得分:0)

看来您的HTML页面上的jQuery引用未加载或不正确,请在HTML页面的<head> here </head>部分添加。

<script src="https://code.jquery.com/jquery-3.1.0.js"></script>