Execute shell script from Flask on button press

Viewed 185

I am learning how to use flask as a backend for web apps, and have created a simple example for myself. There is a Python program that I want to run through a shell script. Following are the Python codes (main.py):

for i in range(0,10):
    print(i)

Following is the shell script to run the above Python program (run.sh):

#!/bin/sh

python3 main.py

Here is the Flask code I have written so far (server.py):

from flask import Flask, render_template

app = Flask(__name__)

@app.route("/")
@app.route("/home")
def home_page():
    return render_template('home.html')

@app.route("/main")
def main_page():
    return render_template('main.html')

So, on the home page (home.html) there is a button that will take the user to the main page (main.html).

Here is what I need help with:
On the main page (main.html) there is a button that I want to use to execute the run.sh script to run the main.py program and display the output on the main page (main.html).

Following is the home.html:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
    <title>Hello, world!</title>
  </head>
  
  <body>
  
    <h1>Home Page</h1>
    <a class="btn btn-primary" href="{{ url_for('main_page') }}" role="button">Go to Main</a>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
  </body>

</html>

and main.html so far:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

    <title>Main Page</title>
  </head>
  <body>
  
    <button class="btn btn-primary" type="submit">Start</button>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
  </body>
</html>

Can anyone guide me as to how I can achieve this?

0 Answers
Related