Flask - 在按钮 OnClick 事件上调用 python 函数 [英] Flask - Calling python function on button OnClick event

查看:102
本文介绍了Flask - 在按钮 OnClick 事件上调用 python 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Python 和 Flask 的新手.我有一个带按钮的 Flask Web 应用程序.当我点击按钮时,我想执行一个 python 方法而不是一个 Javascript 方法.我该怎么做?

I am new to python and Flask. I have a Flask Web App with a button. When I click on the button I would like to execute a python method not a Javascript method. How can I do this?

我见过使用 python 的例子,它使用这样的表单标签将我重定向到一个新页面

I have seen examples with python where it redirects me to a new page using a form tag like this

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

但我不希望它把我重定向到一个新页面.我只是想让它执行 python 方法.我正在为 Raspberry Pi 机器人汽车制作这个.当我按下前进按钮时,我希望它运行向前转动车轮的方法.

but I don't want it to redirect me to a new page. I just want it to execute the python method. I am making this for a Raspberry Pi robot car. When I press the forward button, I want it to run the method to Turn wheels forward.

按钮 HTML 代码 (index.html)

Button HTML Code (index.html)

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

简单的 app.py 代码 - move_forward() 方法位于此处

simple app.py Code - move_forward() method located here

#### 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 方法,我将不胜感激.

I have seen similar questions to mine on Stackoverflow, but they don't seem to answer my question or I am unable to understand the answer. If someone could please provide me a simple way to call a Python method on button click event, it would be greatly appreciated.

我看过的其他问题:

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

--用按钮调用python函数

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

推荐答案

在 AJAX 的帮助下,您可以简单地做到这一点...这是一个调用 python 函数的示例,该函数在不重定向或刷新页面的情况下打印 hello.

解决方案

在 app.py 中放置在代码段下方.

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.

您的 json.html 页面应如下所示.

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

在这里,当您按下控制台中的 Test simple 按钮时,您可以看到Hello"显示没有任何刷新.

Here when you press the button Test simple in the console you can see "Hello" is displaying without any refreshing.

这篇关于Flask - 在按钮 OnClick 事件上调用 python 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆