-1

I am trying to get HTML/webpage interface to run a python script I wrote that generates a graph and saves it in a local directory. I would like to click a single button and have the python code run, generate the graph and save it in a folder which then HTML could embed it on the HTML page. My issue is this code isn't working, the code is not run and no new graph is generated. Both the HTML and Python file (Create_Chart.py) are in the same folder.

Python code

globals().clear()
import numpy as np 
import matplotlib.pyplot as plt
import os


rand=np.random.normal(100,1,size=[100,1])
chart=plt.plot(rand)



plt.savefig(r'C:\Users\...\example_chart.png')

HTML/Javascript code

<!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({url: "Create_Chart.py",context: document.body}).done(function() {alert('finished python script');;});
        }
    </script>
  </body>
</html>

I am trying to follow the example from this other stackoverflow thread. What am I doing wrong? How can I execute a python script from an html button?

The javascript code is being called from the following link 'http://code.jquery.com/jquery-3.3.1.min.js'. Do I need to install Jquery on my local computer?

jessica
  • 1,325
  • 2
  • 21
  • 35
  • 1
    You can use Django or Flask : [`Run Python script on clicking HTML button`](https://www.youtube.com/watch?v=ERMRVORGvZM) – codester_09 Nov 06 '22 at 18:40

1 Answers1

1

You'll need a webserver software (as in nginx) which understands how to run python scripts (as in a WSGI application). The script then needs to be something that understands HTTP. Your script needs then to answer with an HTTP response.

Since you're asking a question on that level, these are many concepts. I suggest you to watch into Django or FastAPI (Python web frameworks; google them). Those come with inbuild test webservers and get you started.

Ric Hard
  • 599
  • 4
  • 12