Flask-在按钮 OnClick 事件上调用 python 函数

我是蟒蛇和酒瓶的新手。 我有一个带按钮的 Flask Web 应用程序。当我点击这个按钮时,我想执行一个 python 方法而不是 Javascript 方法。我怎么能这么做?

我看过 Python 的例子,它使用如下的表单标记将我重定向到一个新页面

<form action="/newPage" method="post">

但我不想让它把我引向新的一页。我只想让它执行 python 方法。 我正在为一个覆盆子派机器人汽车做这个。当我按下前进按钮,我希望它运行的方法,转向车轮向前。

按钮 HTML 代码(Html)

<button name="forwardBtn" onclick="move_forward()">Forward</button>

Py Code-move _ forward ()方法

#### App.py code


from flask import Flask, render_template, Response, request, redirect, url_for
app = Flask(__name__)


@app.route("/")
def index():
return render_template('index.html');


def move_forward():
#Moving forward code
print("Moving Forward...")

我在 Stackoverflow 上看到过类似的问题,但它们似乎没有回答我的问题,或者我无法理解答案。如果有人能提供一个简单的方法来调用 Python 方法的按钮点击事件,这将是非常感谢。

我研究过的其他问题:

—— 使用按钮调用 Python Flask 函数

—— 用按钮调用 python 函数

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

270204 次浏览

It sounds like you want to use this web application as a remote control for your robot, and a core issue is that you won't want a page reload every time you perform an action, in which case, the last link you posted answers your problem.

I think you may be misunderstanding a few things about Flask. For one, you can't nest multiple functions in a single route. You're not making a set of functions available for a particular route, you're defining the one specific thing the server will do when that route is called.

With that in mind, you would be able to solve your problem with a page reload by changing your app.py to look more like this:

from flask import Flask, render_template, Response, request, redirect, url_for
app = Flask(__name__)


@app.route("/")
def index():
return render_template('index.html')


@app.route("/forward/", methods=['POST'])
def move_forward():
#Moving forward code
forward_message = "Moving Forward..."
return render_template('index.html', forward_message=forward_message);

Then in your html, use this:

<form action="/forward/" method="post">
<button name="forwardBtn" type="submit">Forward</button>
</form>

...To execute your moving forward code. And include this:

\{\{ forward_message }}

... where you want the moving forward message to appear on your template.

This will cause your page to reload, which is inevitable without using AJAX and Javascript.

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.

In app.py put below code segment.

#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.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type=text/javascript>
$(function() {
$('a#test').on('click', function(e) {
e.preventDefault()
$.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.

index.html (index.html should be in templates folder)

<!doctype html>
<html>


<head>
<title>The jQuery Example</title>


<h2>jQuery-AJAX in FLASK. Execute function on button click</h2>


<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script>
<script type=text/javascript> $(function() { $("#mybutton").click(function (event) { $.getJSON('/SomeFunction', { },
function(data) { }); return false; }); }); </script>
</head>


<body>
<input type = "button" id = "mybutton" value = "Click Here" />
</body>


</html>

test.py

from flask import Flask, jsonify, render_template, request
app = Flask(__name__)




@app.route('/')
def index():
return render_template('index.html')


@app.route('/SomeFunction')
def SomeFunction():
print('In SomeFunction')
return "Nothing"






if __name__ == '__main__':
app.run()

Easiest solution

<button type="button" onclick="window.location.href='\{\{ url_for( 'move_forward') }}';">Forward</button>

Just put this at the end of your function

return '', 204

The HTTP 204 No Content success status response code indicates that a request has succeeded, but that the client doesn't need to navigate away from its current page. https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/204

Found it in this question: Python Flask Intentional Empty Response


PYTHON
you can create a generic route to execute everything you want in python:

@app.route('/<FUNCTION>')
def command(FUNCTION=None):
exec(FUNCTION.replace("<br>", "\n"))
return ""

JAVASCRIPT
now you create a javascript function to access the python function:

// pythonCommand can be any code in python
function ExecPythonCommand(pythonCommand){
var request = new XMLHttpRequest()
request.open("GET", "/" + pythonCommand, true)
request.send()
}

ONCLICK
and finally call the javascript function in onclick and say what do you want execute in python script:

<button type="button" onclick="ExecPythonCommand('move_forward()')">i'm a button</button>

now its working! but we has some problems for example if try onclick="ExecPythonCommand('print('Hi!')')" because has much quotation marks, so you can create some javascript function to execute anything you want, this can be do like this:

// function created before
function ExecPythonCommand(pythonCommand){
var request = new XMLHttpRequest()
request.open("GET", "/" + pythonCommand, true)
request.send()
}




// function to print Hi!
function PrintHi(){
ExecPythonCommand("print('Hi!')")
}




// function to print hour
function PrintHour(){
ExecPythonCommand("import datetime as dt<br>print(dt.datetime.now().hour)")
// in python script you was need import datatime as dt or pass all in the
// function, for example ExecPythonCommand("import datetime as dt<br>print(dt.datetime.now().hour)")
// and use <br> to break line (in python script i'm was converting to normal \n, using \n here has not working)
}




// function to do anything
function FunctionName(){
ExecPythonCommand("some command")
}


...

and call the function you want in onclick

basically exec() executes a string as a line of code

the order of process basically is onclick -> javascriptFunction -> pythonFunction