私はpythonとFlaskの初心者です。 私はボタンとFlask Web Appを持っています。私がボタンをクリックすると、私はJavascriptのメソッドではなく、Pythonのメソッドを実行したいと思います。どのように私はこれを行うことができますか?
Python を使って、次のようなフォームタグを使った新しいページにリダイレクトさせる例を見たことがあります。
<form action="/newPage" method="post">
しかし、私は新しいページにリダイレクトさせたくはないのです。ただ、Pythonのメソッドを実行させたいだけです。 私はRaspberry Piのロボットカーのためにこれを作っています。前進ボタンを押すと、車輪を前進させるメソッドを実行させたいのです。
ボタンHTMLコード (index.html)
<button name="forwardBtn" onclick="move_forward()">Forward</button>
simple app.py コード - 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のメソッドを呼び出す簡単な方法を教えていただければ、非常にありがたいです。
その他に見たことのある質問
--https://stackoverflow.com/questions/30899484/python-flask-calling-functions-using-buttons
--https://stackoverflow.com/questions/40583347/calling-a-python-function-with-a-button
--https://stackoverflow.com/questions/21566649/flask-button-run-python-without-refreshing-page
AJAXの助けを借りれば、簡単にできますよ。 ここでは、ページをリダイレクトしたり更新したりせずに、helloを表示するpython関数を呼び出す例を示します。
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"
そして、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>
ここで、Test simpleというボタンを押すと、コンソールに"Hello".と表示されます。 がリフレッシュされることなく表示されています。
このWebアプリケーションをロボットのリモコンとして使用したいようですが、核となる問題は、アクションを実行するたびにページを再読み込みしたくないということです。
Flaskについて、いくつか誤解されているようですね。 1つは、1つのルートに複数の関数をネストすることはできません。 特定のルートで利用可能な関数のセットを作るのではなく、そのルートが呼び出されたときにサーバーが行う特定の1つのことを定義しているのです。
これを踏まえて、app.pyを以下のように変更すれば、ページの再読み込みの問題を解決することができます。
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);
そして、htmlの中で、これを使います。
<form action="/forward/" method="post">
<button name="forwardBtn" type="submit">Forward</button>
</form>
...前進するコードを実行します。 そして、これを含めます。
{{ forward_message }}
... テンプレート上の前進するメッセージを表示させたい場所。
この場合、AJAXやJavascriptを使用しないと避けられない、ページの再読み込みが発生します。
index.html (templates フォルダにあるはずです。)
<!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()