【问题标题】:Flask - Calling python function on button OnClick eventFlask - 在按钮 OnClick 事件上调用 python 函数
【发布时间】:2017-07-24 21:32:26
【问题描述】:

我是 python 和 Flask 的新手。 我有一个带有按钮的 Flask Web App。当我单击按钮时,我想执行 python 方法而不是 Javascript 方法。我该怎么做?

我看到过使用 python 的示例,它使用这样的表单标签将我重定向到新页面

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

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

按钮 HTML 代码 (index.html)

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

简单的 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 方法,将不胜感激。

我看过的其他问题:

--Python Flask calling functions using buttons

--Calling a python function with a button

--Flask Button run Python without refreshing page?

【问题讨论】:

  • 希望你已经解决了这个问题(根据你删除your question的事实)。我的意思是,您的输入形状是 (120, 320, 3),但您正在为模型提供形状为 n x 1(或您的 batchSize 的任何形状)的数组。

标签: javascript python html flask raspberry-pi


【解决方案1】:

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

在 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').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>

在这里,当您在控制台中按下按钮 Test simple 时,您可以看到“Hello” 正在显示而没有任何刷新。

【讨论】:

  • 这个解决方案的一个问题是a href 参数被覆盖。这意味着,例如,如果您想使用 a 标记将用户跳转到页面上的不同位置,它将激活 python 功能,但不再用作链接。这可以通过额外的 javascript 解决,但我不确定是否有基于烧瓶或 HTML 的解决方案:stackoverflow.com/q/59342706/6924364
  • 我有一个与这个非常相似的代码。如果我想通过 POST 方法等从按钮向background_process_test() 函数传递一些数据,我该怎么办?
  • @mazunki 如果你想将参数传递给 background_process_test 函数,你可以将 onclick 事件添加到按钮并使用它的参数调用函数,这对我有用,而无需添加 ajax 脚本
【解决方案2】:

听起来您想将此 Web 应用程序用作机器人的遥控器,核心问题是您不希望每次执行操作时都重新加载页面,在这种情况下,您的最后一个链接张贴回答你的问题。

我认为您可能对 Flask 有一些误解。一方面,您不能在单个路由中嵌套多个函数。您不是在为特定路由提供一组函数,而是在定义调用该路由时服务器将执行的一项特定操作。

考虑到这一点,您可以通过将 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 的情况下不可避免的。

【讨论】:

  • 找不到文件!
  • @SalihKaragoz 您应该将 index.html 放入“模板”文件夹中。
【解决方案3】:

最简单的解决方案

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

【讨论】:

    【解决方案4】:

    index.html(index.html 应该在模板文件夹中)

    <!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()
    

    【讨论】:

      猜你喜欢
      • 2021-09-20
      • 1970-01-01
      • 2015-04-27
      • 2015-09-03
      • 2018-06-27
      • 1970-01-01
      • 1970-01-01
      • 2015-05-14
      相关资源
      最近更新 更多