Using Flask to Trigger Python Function on Button Click Event

Posted by

Flask is a popular web framework for building web applications using Python. One common requirement in web development is to call a Python function when a button is clicked on a web page. In this article, we will see how to achieve this using Flask.

First, let’s create a simple Flask application with a route that renders a basic HTML template containing a button that calls a Python function when clicked.

“`python
from flask import Flask, render_template

app = Flask(__name__)

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

def my_function():
print(‘Python function called’)

if __name__ == ‘__main__’:
app.run()
“`

Next, let’s create an HTML template called `index.html` in a `templates` folder in the same directory as our Flask app. This template will contain a button that calls the Python function `my_function` when clicked.

“`html

Flask – Calling Python Function on Button OnClick Event

Click the button below to call a Python function

function callPythonFunction() {
fetch(“/call-python-function”)
}

“`

In the HTML code above, we have defined a button with an `onclick` event that calls the JavaScript function `callPythonFunction`. Inside this JavaScript function, we use the `fetch` API to make a GET request to the endpoint `/call-python-function`.

Now, let’s update our Flask app to add a new route `/call-python-function` that calls the Python function `my_function`.

“`python
from flask import Flask, render_template

app = Flask(__name__)

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

@app.route(‘/call-python-function’)
def call_python_function():
my_function()
return ‘Python function called successfully’

def my_function():
print(‘Python function called’)

if __name__ == ‘__main__’:
app.run()
“`

With this setup, when the button in our HTML template is clicked, the JavaScript function `callPythonFunction` will make a GET request to the `/call-python-function` endpoint in our Flask app. This will trigger the `call_python_function` view function, which in turn will call the `my_function` Python function and print ‘Python function called’ in the console.

In conclusion, we have demonstrated how to call a Python function on a button `onClick` event in a Flask application using JavaScript and the `fetch` API. This approach allows for seamless communication between the client-side and server-side code in a web application.