【发布时间】:2020-07-26 11:23:15
【问题描述】:
我有一个 html 页面 custom.html 和一个 python 脚本 test.py(都在下面截图)。 html 页面只有一个按钮,应该触发 python 脚本打印一行(在我的下一个 python 脚本中,我希望它做更多,但这是我的起点)。
在 Chrome 的开发人员工具下,一旦我单击按钮,我就会收到由 Jquery 发起的 GET 404 错误。非常感谢任何有关从我的 html 按钮成功激活 python 脚本的建议。
我的 test.py 脚本很简单
print("Successful line print")
这是我的 custom.html 文档
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Page Title</title>
<link rel="stylesheet" type="text/css" href="../static/css/style2.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<pre>
</pre>
<body>
<div>
<div>
<button style="text-align: center; margin-bottom: 150px" class="search-btn" type="button" value=" Run Script " onclick="goPython()">Trigger Python
<script>
function goPython() {
$.ajax({
url: "../folder/test.py",
context: document.body
}).done(function() {
alert('finished python script');;
});
}
</script>
</button>
</div>
</div>
</body>
</html>
编辑:我将代码添加到 Google App Engine 处理 URL 调用和导入 Flask 所需的 main.py 脚本中。
from flask import Flask, request, render_template
app = Flask(__name__)
@app.route("/")
def index():
return render_template('index.html')
@app.route("/learn.html")
def learn():
return render_template('learn.html')
@app.route("/custom.html")
def custom():
return render_template('custom.html')
if __name__ == "__main__":
app.run()
编辑 2,在尝试@Dustin Ingram 的回答后:
这是我的 custom.html 的新代码
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Page Title</title>
<link rel="stylesheet" type="text/css" href="../static/css/style2.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<div>
<div>
<button style="text-align: center; margin-bottom: 150px" class="search-btn" type="button" value=" Run Script " onclick="goPython()">Click Here
<script>
function goPython() {
$.ajax({
url: "/trigger-python",
context: document.body
}).done(function() {
alert('finished python script');;
});
}
</script>
</button>
</div>
</div>
</body>
</html>
我做了一个简单的test.py,只是为了测试html按钮点击激活python脚本的能力
from flask import Flask
app = Flask(__name__)
@app.route("/trigger-python")
def print_something():
print("Successful line print")
return 'OK'
print_something()
if __name__ == '__main__':
app.run(host='127.0.0.1', port=8080, debug=True)
修复在 AJAX 中调用的 URL 后,单击按钮时仍然出现相同的 404 错误。以下是更新后的 Chrome 开发者工具屏幕截图。
【问题讨论】:
标签: python html ajax google-app-engine google-cloud-platform