【发布时间】: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