3

I am currently trying to create a website with Flask that contains just one button (for now). If I press that button I want to run a python script from a specific path or just the project folder. I already saw some posts about the same topic but none of them could really help me.

I already have some code. This is my Flask app.py

from flask import Flask, render_template, jsonify
import test

app = Flask(__name__)

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


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

And that's my index.html

<!DOCTYPE html>
<html>
 <head>
 </head>
 <body>
   <input type="button" id='script' name="scriptbutton" value=" Run Script " onclick="goPython()">

   <script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>

   <script>
       function goPython(){
           $.ajax({
             type: 'POST',
             url: "/test.py",
             //or some other path like /scripts/test.py
             dataType: "text",
             success: function (data) {
               alert(data)
             },
             error: function (data) {
               alert(data)
             }
           });
       }
   </script>
 </body>
</html>

If I run my flask website and click the button I want to execute my test.py saved in my project folder or somewhere else. I don't know if it is possible that way or if there is a better solution. Right now I am still trying with flask but I can't get my test.py to run. When I press the button it just shows me an alert with [object Object]

Basically what I am trying to build is a website with buttons, like a service that runs my scripts in the background that can sometimes take more time to finish. I am not sure if I am misunderstanding the use of ajax in this case. Any help would be nice.

shhsh12
  • 47
  • 1
  • 1
  • 2
  • 1
    The ajax is the frontend , what you need to do is to pass the information to the backend for the script to run, which is where the url and the post request does its job it hits the backend at `/tasks.py` url of the flask server and then you need to handle this request in your code , to run the script you want to execute – Albin Paul Apr 08 '19 at 08:18
  • Okay so I have to implement my script in my backend anyways? Because I am looking for a solution to just call my py from a specific path. – shhsh12 Apr 08 '19 at 08:36
  • 1
    you dont have to implement your script you have to call the script in the backend, which can be passed as argument in the url as to which script you want to call – Albin Paul Apr 08 '19 at 08:41
  • Ah, I see. I was misunderstanding ajax as my frontend. I thought I can just call my py in my html with Ajax. I completely forgot to handle the request in my backend. Thank you. – shhsh12 Apr 08 '19 at 09:04

2 Answers2

3

A simple solution to run code on button press could be the following. If you want to run tasks in background, have a look at celery or threading in flask.

from flask import Flask, render_template, jsonify
import test

app = Flask(__name__)

@app.route('/', methods=['POST', 'GET'])
def index():
    if request.method == "POST":
        <insert python script here>

    return render_template('index.html')

change your template to this:

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <form  method = "post">
     <input type="button" id='script' name="submit" value="Run Script">
    </form>
  </body>
</html>
gittert
  • 1,238
  • 2
  • 7
  • 15
  • That's a simple solution but I need to implement my python script in my app.py. That's not exactly what I was planning to do because I have other scripts and I want to keep my app.py simple. I thought about calling the python scripts without having to actually implement them. – shhsh12 Apr 08 '19 at 08:33
  • 1
    I found a question here about using subprocess with Flask, that could be useful to you, perhaps : https://stackoverflow.com/questions/40388238/popen-in-flask-starts-python-interpreter – Orysza Apr 08 '19 at 08:51
1

Some examples using Flask functions, jQuery and Bootstrap (not necessary, only for button formatting). Hope this could help you.

Python (in the app script):

@app.route('/do_something')
def do_something():
  """
  Do something on button press.
  """
  # your code
  return res

JavaScript:

var btnName = function() {
  $.get('/do_something',
    function(x) {
      $("#resBtnHere").html(x);
    }
  )
}
btnName()

Button in HTML:

<button
  type="button"
  class="btn btn-primary"
  onclick="btnName()"
>Click here
</button>

In html, result of your function on button press (if needed):

<p id="resBtnHere"></p>
Audwin Oyong
  • 2,247
  • 3
  • 15
  • 32
Orysza
  • 574
  • 1
  • 5
  • 10