Trigger python code from Browser button click?Answer below

#1

Below is a basic way tried and tested with flask application thought to share.

Considering flask is installed
Create directories
mkdir /home/pi/flask/
mkdir /home/pi/flask/static/
mkdir /home/pi/flask/template/

main.py #this will start application can locate under flask dir (sudo python main.py &)

#!/usr/bin/env python
from flask import Flask, flash, redirect, render_template, request, session, abort
import os
import time
import subprocess
import sys
import os
import argparse
import glob

app = Flask(__name__)

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


@app.route('/task/',methods = ['POST', 'GET'])
def table1():
        print("Task started")
                subprocess.call('/home/pi/flask/task.sh')  #this call the os script 
                return render_template('index.html')

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')

/home/pi/flask/task.sh #will look like

#!/bin/bash
#python code you want to execute
python /home/pi/flask/task.py
#anything ,,,,,,,


And in template directory create index.html

<!DOCTYPE html>
<html>
<head>
<style>
</style>
<body style="background-color:powderblue;">
</body>
<br><br>
<form action="/task/" method="post">
    <button style="height:150px;width:150px">Task</button>
</form>
<br><br><br>

start the main.py
That all go to browser and with click of button control gopigo

Ip address on gopigo:5000
Capturejljl

/Chetuk

1 Like

#2

Some questions from a “Dexter Industries Raspian For Robots” and GoPiGo3 perspective:

  1. How does Flask differ from the Apache2 server already installed on R4R?
  2. Does Flask coexist well with the R4R Apache2 and supported R4R “home page” (with noVNC / console buttons)

@RobertLucian

  1. Would it be possible, more “GoPiGo-ish”, to add user task button/application mapping to a “custom button div” on the R4R “home page” and not need Flask?
  2. If so, perhaps DI would add a “user button div” and a “user output div” on the R4R “home page” and publish an example how to publish the user button, connect the user button to a user application, and how the app can publish to the “user output div”.
  3. Would dynamic HTML be possible in the “user output div” area with the R4R base installation?
  4. Does DI have a preferred user web interface / programming method for R4R?
0 Likes

#3

Is this the way to install it? (“install flask on Apache” instructions at http://flask.pocoo.org/docs/1.0/deploying/mod_wsgi/ )

0 Likes

#4

Below website is reference
https://projects.raspberrypi.org/en/projects/python-web-server-with-flask

I noticed the flask was already available on gopigo.
This is a customize way to control python script from browser also remotely.
Currently I am controlling from my ipad.

Was able to access from local system via chrome browser

Cheers!

0 Likes