簡體   English   中英

在Flask中運行python腳本

[英]running a python script within 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 : http://127.0.0.1:5000/test?a=10&b=25 : 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(…)

請參考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')

請嘗試以下代碼,讓我知道您是否正在尋找它:

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

似乎您在該HTML頁面上的jQuery參考未加載或不正確,請在HTML頁面的<head> here </head>部分中添加此參考。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM