gpt4 book ai didi

python - Flask Button 在不刷新页面的情况下运行 Python?

转载 作者:太空狗 更新时间:2023-10-29 22:26:29 26 4
gpt4 key购买 nike

我刚刚开始使用 python 和 flask(用于树莓派)。我想要一个 Web 应用程序来执行一些 Python 代码来平移和倾斜相机并显示视频流。

到目前为止,我的 flask 代码是:

from flask import Flask, render_template
import time
import serial
#ser = serial.Serial('/dev/ttyUSB0',9600)
app = Flask(__name__)
@app.route('/')
@app.route('/<cmd>') #each button in my html redirects to a specified directory
def execute(cmd=None):
if cmd == "down":
print "Moving Down"
#ser.write("D")

if cmd == "up":
print "Moving Up"
#ser.write("U")

if cmd == "left":
print "Moving Left"
# ser.write("L")

if cmd == "right":
print "Moving Right"
#ser.write("R")

if cmd == "reset":
print "Reseting.."
#ser.write("X")

return render_template("main.html")


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

问题是我的代码依赖于每个按钮重定向到一个新目录,虽然这确实有效,但它每次都会刷新页面,这意味着我的嵌入式视频会重新加载并再次缓冲。有没有更好的方法来检测按钮按下然后使用 flask 执行 python 代码?

最佳答案

我会把它分成两条路线,以便更容易看到你必须做什么:

LEFT, RIGHT, UP, DOWN, RESET = "left", "right", "up", "down", "reset"
AVAILABLE_COMMANDS = {
'Left': LEFT,
'Right': RIGHT,
'Up': UP,
'Down': DOWN,
'Reset': RESET
}

@app.route('/')
def execute():
return render_template('main.html', commands=AVAILABLE_COMMANDS)

@app.route('/<cmd>')
def command(cmd=None):
if cmd == RESET:
camera_command = "X"
response = "Resetting ..."
else:
camera_command = cmd[0].upper()
response = "Moving {}".format(cmd.capitalize())

# ser.write(camera_command)
return response, 200, {'Content-Type': 'text/plain'}

然后在您的模板中,您只需要使用一些 JavaScript 来发送请求:

{# in main.html #}
{% for label, command in commands.items() %}
<button class="command command-{{ command }}" value="{{ command }}">
{{ label }}
</button>
{% endfor %}

{# and then elsewhere #}
<script>
// Only run what comes next *after* the page has loaded
addEventListener("DOMContentLoaded", function() {
// Grab all of the elements with a class of command
// (which all of the buttons we just created have)
var commandButtons = document.querySelectorAll(".command");
for (var i=0, l=commandButtons.length; i<l; i++) {
var button = commandButtons[i];
// For each button, listen for the "click" event
button.addEventListener("click", function(e) {
// When a click happens, stop the button
// from submitting our form (if we have one)
e.preventDefault();

var clickedButton = e.target;
var command = clickedButton.value;

// Now we need to send the data to our server
// without reloading the page - this is the domain of
// AJAX (Asynchronous JavaScript And XML)
// We will create a new request object
// and set up a handler for the response
var request = new XMLHttpRequest();
request.onload = function() {
// We could do more interesting things with the response
// or, we could ignore it entirely
alert(request.responseText);
};
// We point the request at the appropriate command
request.open("GET", "/" + command, true);
// and then we send it off
request.send();
});
}
}, true);
</script>

关于python - Flask Button 在不刷新页面的情况下运行 Python?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21566649/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com