Flask Button运行Python而不刷新页面? [英] Flask Button run Python without refreshing page?
问题描述
现在,
pre $ 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在我的html中的按钮重定向到指定的目录
def执行(cmd =无):
if cmd ==down:
printMoving Down
#ser.write (D)
if cmd ==up:
print向上移动
#ser.write(U)
如果cmd ==left:
printMoving Left
#ser.write(L)
if cmd ==right:
打印右移
#ser.write(R)
if cmd ==reset:
打印Reseting ..
# ser.write(X)
return render_template(main.html)
if __name__ ==__main__:
app.run(h ost ='0.0.0.0',port = 8080,debug = True)
依靠每个按钮重定向到一个新的方向,而这个工作正常,每次刷新页面,这意味着我的嵌入式视频重新加载和再次缓冲。有没有更好的方式来检测一个按钮,然后用烧瓶执行python代码?
我会将其分成两条路线,以便更轻松地查看您所要做的事情。 b
$ b
左,右,上,下,复位=左,右,上,下,复位
$ AVAILABLE_COMMANDS = {
'Left':LEFT,
'Right':RIGHT,
'Up':UP,
'Down':DOWN,
' Reset':RESET
$ b $ app_route('/')
def execute():
return render_template('main.html',commands = AVAILABLE_COMMANDS)
@ app.route('/< cmd>)
def命令(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'}
然后在你的模板里,你就是ne编辑使用一些JavaScript发送请求:
$ b
{#in main.html#}
{%为label,命令在commands.items()%}
{{label}}
< / button>
{%endfor%}
{#然后在别处#}
< script>
//在页面加载后,只运行下一个* $ addEventListener(DOMContentLoaded,function(){
//使用一类命令获取所有元素
//(我们刚创建的所有按钮都有)
var commandButtons = document.querySelectorAll(。command);
for(var i = 0,l = commandButtons.length; i< ; l; i ++){
var button = commandButtons [i];
//对于每个按钮,监听click事件
button.addEventListener(click,function ){
//当点击发生时,停止按钮
//提交表单(如果有的话)
e.preventDefault();
var clickedButton = e.target;
var command = clickedButton.value;
//现在我们需要发送数据到我们的服务器
//不用重新加载页面 - 这个是
的域// AJAX(异步JavaScript和XML)
//我们将创建一个新的请求对象
//并设置为响应添加一个处理程序
var request = new XMLHttpRequest();
request.onload = function(){
//我们可以用响应
//做更多有趣的事情,或者我们可以完全忽略它
alert(request.responseText) ;
};
//我们将请求指向相应的命令
request.open(GET,/+ command,true);
//然后发送
request.send();
});
}
},true);
< / script>
i am just getting started into python and flask (for the raspberry pi). I want a web application that would execute some python code to pan and tilt a camera and display a video stream.
My code uptil now for flask is:
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)
The problem is my code relys on the each button redirecting to a new directry, while this does work well, it refreshes the page each time which means my embeded video reloads and buffers again. Is there a better way of detecting a button press and then executing python code using flask?
I would split it out into two routes to make it easier to see what you have to do:
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'}
Then in your template you just need to use some JavaScript to send off the request:
{# 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>
这篇关于Flask Button运行Python而不刷新页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!