Home > Back-end >  Run python script at the click of an html button (Flask/Django)
Run python script at the click of an html button (Flask/Django)

Time:11-10

I have a very simple python code that retrieves the share price of some stocks. I have managed to include that in Django/Flask so I can see this in a html page. I would like to create an html button that when I click on it it runs the python script and the share prices refresh (and remain on the same html page e.g. index.html) however I can't make it work. Can you please help with the html code for the button and the piece of code that I need to add to the app to make it work?

CodePudding user response:

If you have written a class, or a method, then you can just call it an store the returned value in a variable and pass it to the html file using jinja2.

would be something like:

return render_template("index.html", parameter1 = returned_value)

and in your html file:

<p>{{ parameter1 }}</p>

Take a look: https://hackersandslackers.com/flask-jinja-templates/

CodePudding user response:

The only way to do what you want is by a remote call to the server. But by no mean you can refresh your list entirely client-side, especially with Python only.

What you must do if you really want not to reload the page is to :

  • client-side : make a request to the server from a Javascript function then fetch the response and refresh your share prices the incoming data
  • server-side : create a new view that will not render a template then return an html response, but serialize your data and return a JSON response.

That's all I can say to you. Do not expect the Stackoverflow community to give you a ready-to-use answer before you have brought a proof that you tried by yourself.

  • Related