【问题标题】:"GET" get text of script, "POST" results in "405 method not allowed", I _did_ methods=['GET', 'POST'] (from JavaScript through Flask to Python)“GET”获取脚本文本,“POST”导致“405 method not allowed”,我_did_methods=['GET','POST'](从JavaScript到Flask到Python)
【发布时间】:2017-09-22 16:00:32
【问题描述】:

在 Raspberry Pi 中,我使用 Flask 提供网页,该网页使用 JavaScript 发布到 Python 脚本。

文件夹结构:

/home/pi/Elithion/app.py
/home/pi/Elithion/templates/index.html
/home/pi/Elithion/static/wificonfig.py

app.py(使用 Flask 的 Python 代码)

from flask import Flask, render_template, url_for

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def index():
    return render_template('index.html')

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

index.html,JavaScript:

function ReqWifiConfig(selectedWiFiNetwork, wiFiPassword) { // Request setting the WiFi configuration

    // Constants
    var WifiConfigScript = '/static/wificonfig.py';
    var ContentKey = 'Content-type';
    var ContentVal = 'application/x-www-form-urlencoded';

    // Send the wifi login credentials to the Python script using AJAX
    var xmlhttp = new XMLHttpRequest();     
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200){
            ...
        }   
        else if (xmlhttp.readyState==4) {
            alert(xmlhttp.status + xmlhttp.statusText); 
        }
    }
    xmlhttp.open("POST", WifiConfigScript, true);  
    xmlhttp.setRequestHeader(ContentKey, ContentVal);
    var postData = 'nw=' + selectedWiFiNetwork + '&pw=' + wiFiPassword;
    xmlhttp.send(postData);     
}

这会在浏览器中显示此警报:

127.0.0.1:5000 says: 405METHOD NOT ALLOWED

终端中的这条消息:

127.0.0.1 - - (date) "POST / static/wificonfig.py HTTP/1.1 405 -

如果我将“POST”更改为“GET”,它会返回脚本中的文本,所以我知道路径是正确的。

我检查了这些 StackOverflow 答案,但它们没有帮助,因为我确实有正确的路径,我没有使用 HTML 表单,并且 CORS 不适用:

【问题讨论】:

  • 当你的路由只是/时,你为什么要发布到'/static/wificonfig.py'?
  • 因为那是脚本所在的位置,也是 Flask 希望您放置文件(图像等)的位置。现在,如果我应该将脚本放在其他地方,我渴望学习。你认为这是我的问题吗?
  • @Daniel Roseman 因为如果我将脚本移动到 /home/pi/Elithion/,并将行更改为 var WifiConfigScript = '/wificonfig.py';我得到一个 404。我也试过 var WifiConfigScript = 'wificonfig.py';和 var WifiConfigScript = 'Elithion/wificonfig.py';

标签: javascript python flask


【解决方案1】:

您不能发布到静态文件。如果您有要运行的 Python 代码,您可以在 Flask 视图函数中执行此操作。将您的脚本移动到您的应用程序旁边,使其可导入、导入、调用并返回响应。

from flask import request, jsonify
from import wificonfig import do_config

@app.route('/wificonfig', methods=['POST'])
def wificonfig():
    result = do_config(nw=request.form['nw'], pw=request.form['pw'])
    return jsonify(result)

模板中的 JavaScript 发布到此路由,而不是 wificonfig.py。使用 url_for 生成 URL 并使用 tojson,因为您使用的是 JavaScript 中的值。

var wifiConfigScript = {{ url_for('wificonfig')|tojson }};

【讨论】:

    【解决方案2】:

    解决了,感谢 davidism 的澄清。

    文件夹结构:

    /home/pi/Elithion/app.py
    /home/pi/Elithion/templates/index.html
    /home/pi/Elithion/wificonfig.py
    

    app.py(使用 Flask 的 Python 代码)

    from flask import Flask, render_template, request
    import wificonfig
    
    app = Flask(__name__)
    
    # Show the HTML page
    @app.route('/')
    def index():
        return render_template('index.html')
    
    # Service the POST request
    @app.route('/postService', methods=['POST'])
    def postService():
        wifiStatus = 'fail'
        if request.method == 'POST':
            nw = request.form['nw'] # WiFi network
            pw = request.form['pw'] # WiFi Password
            wifiStatus = wificonfig.configwifi(nw, pw)
        return wifiStatus
    
    if __name__ == '__main__':
        app.run(debug=True, host='0.0.0.0')
    

    wificonfig.py 脚本:

    def configwifi(nw, np):
        """ Sign onto the WiFi specified network with the given password """
        # ... Code to sign onto the WiFi network
        return 'OK'
    

    index.html,JavaScript:

    function ReqWifiConfig(selectedWiFiNetwork, wiFiPassword) { // Request setting the WiFi configuration
    
        // Constants
        var  WifiConfigScript = '/postService';
        var ContentKey = 'Content-type';
        var ContentVal = 'application/x-www-form-urlencoded';
    
        // Send the login credentials to the Python script using AJAX
        var xmlhttp = new XMLHttpRequest();     
        xmlhttp.onreadystatechange=function() {
            if (xmlhttp.readyState==4 && xmlhttp.status==200){
                alert(xmlhttp.status + xmlhttp.statusText); // Returns 'OK'
            }
        }
        xmlhttp.open("POST", WifiConfigScript, true);
        xmlhttp.setRequestHeader(ContentKey, ContentVal);
        var postData = 'nw=' + selectedWiFiNetwork + '&pw=' + wiFiPassword;
        xmlhttp.send(postData);     
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-25
      • 2017-09-30
      • 2020-08-04
      • 2015-07-01
      • 2016-06-15
      相关资源
      最近更新 更多