[英]Flask Button run Python without refreshing page?
I am just getting started into python and flask (for the raspberry pi).我刚刚开始使用 python 和烧瓶(对于树莓派)。 I want a web application that would execute some python code to pan and tilt a camera and display a video stream.
我想要一个 Web 应用程序,它可以执行一些 python 代码来平移和倾斜相机并显示视频流。
My code up until 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 relies on the each button redirecting to a new directory, while this does work well, it refreshes the page each time which means my embedded video reloads and buffers again.问题是我的代码依赖于每个按钮重定向到一个新目录,虽然这很有效,但它每次都会刷新页面,这意味着我的嵌入视频会再次重新加载和缓冲。 Is there a better way of detecting a button press and then executing python code using flask?
有没有更好的方法来检测按钮按下然后使用flask执行python代码?
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:然后在您的模板中,您只需要使用一些 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>
I've got the same problem, and the answer is simple using ajax XmlHttpRequest:我遇到了同样的问题,使用 ajax XmlHttpRequest 的答案很简单:
// send a request, but don't refresh page
xhttp = new XMLHttpRequest();
xhttp.open("GET", "your script action", true);
xhttp.send();
Here's a small example, calling current script with parameters "like", embedded in a function:这是一个小例子,使用嵌入在函数中的参数“like”调用当前脚本:
function likeStuffs()
{
// send a request, but don't refresh page
xhttp = new XMLHttpRequest();
xhttp.open("GET", "?like", true);
xhttp.send();
}
You can simply do this with help of AJAX... Here is a example which calls a python function which prints hello without redirecting or refreshing the page.你可以在 AJAX 的帮助下简单地做到这一点......这是一个调用 python 函数的示例,该函数在不重定向或刷新页面的情况下打印 hello。
In app.py put below code segment.在 app.py 中放在代码段下面。
//rendering the HTML page which has the button
@app.route('/json')
def json():
return render_template('json.html')
//background process happening without any refreshing
@app.route('/background_process_test')
def background_process_test():
print "Hello"
return "nothing"
And your json.html page should look like below.您的 json.html 页面应如下所示。
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type=text/javascript>
$(function() {
$('a#test').bind('click', function() {
$.getJSON('/background_process_test',
function(data) {
//do nothing
});
return false;
});
});
</script>
//button
<div class='container'>
<h3>Test</h3>
<form>
<a href=# id=test><button class='btn btn-default'>Test</button></a>
</form>
</div>
Here when you press the button Test simple in the console you can see "Hello" is displaying without any refreshing.在这里,当您按下控制台中的 Test simple 按钮时,您可以看到“Hello”正在显示而没有任何刷新。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.