Python Flask calling functions using buttons

后端 未结 1 618
野趣味
野趣味 2020-12-14 04:14

Once the button in my flask template is pressed I\'d like it to call a python function defined in app.py that I made to be available to be called within the template by typi

相关标签:
1条回答
  • 2020-12-14 04:50

    If you want to execute your function without generating a request to the server, then your function must be defined in JavaScript. Otherwise, you need to fire an HTTP request.

    Now in your case, if all you're trying to do is enable/disable buttons, it would make sense to do all that in javascript (no need to go to the server).

    Example:

    <button type="button" onclick="disableButton(this)" name="enable">Enable</button>
    

    javascript

    function disableButtonState(elem) {
        if(confirm('Are you sure you want to disable this button?') == true) {
            elem.disabled = true;
            alert("its done.");            
        }
        else { 
            return false;
        }          
    }
    </script>
    

    However if what you want is to call a method on your server that, for example, sends an email, then you should use a form POST/GET or AJAX POST/GET

    Example:

    app.py

    @app.route('/foo', methods=['GET', 'POST'])
    def foo(x=None, y=None):
        # do something to send email
        pass
    

    template

    <form action="/foo" method="post">
        <button type="submit" value="Send Email" />
    </form>
    

    When you click the "Send Email" button an HTTP POST request is sent to "/foo" on your application. Your function foo can now extract some data from the request and do whatever it wants to do on the server side and then return a response to the client web browser.

    It would suggest going through the Flask Tutorial to get a better understanding of client/server interactions when it comes to web applications built with Flask.

    0 讨论(0)
提交回复
热议问题