0

I’m new to web development. I have learned how to make a web sever using flask. What I want to do is make an html button run python code from the web server when it is clicked. Is this even possible? If so, can someone point me to some html examples that can do that?

Update: I think I found some code that might work with what I’m asking. I don’t know for sure if it would work or not.

Here is the link: Call a python function within a html file

If I were to convert the “click a link” aspect of the code to “click a button” would it run my python code on the viewers end, not my end?

NewToPython
  • 97
  • 3
  • 9
  • 1
    you may use standard link to run code in flask and get new page. OR `
    ` also to run code in flask and get new page. OR you need to use JavaScript to run code without loading new page. You can use modern `fetch("/url")` to execute it - but it needs to learn JavaScript. Few days ago I was answering on question how to use it to send data to flask and get result. You could find many questions for this problem.
    – furas May 21 '21 at 01:01

2 Answers2

1

It is Possible in Two ways

  • Create an HTML form and button to submit the form. The from can call the post URL on the flask server

  • Add some javascript to the HTML and call any HTTP method /url that you have created using the flask server.

  • Can you please explain in a little more detail? Sorry, I’m new to some terms. – NewToPython May 21 '21 at 00:42
  • let's say in your Flask application you created a router called "hello" with app.route("/hello") and added a function to it. Now in HTML create a HTML form which action "/hello" and a button to submit the from. e.g. https://www.geeksforgeeks.org/retrieving-html-from-data-using-flask/ – Maitreyee Das May 21 '21 at 00:46
  • I see now how that would send a message to my code from the button click. But how do I run python code on their end once the button is clicked? For example, make it print(“Hello world!”) using Python code. My issue is that it would run the code on my end rather than their end. – NewToPython May 21 '21 at 14:59
  • You can't run python in the browser. What you have to do is generate a HTML file with the content you want to show based on the click and push it to the browser . If all you want to do it show something on the browser better approch is add some javascript – Maitreyee Das May 21 '21 at 16:15
0

You can use button with form or with JavaScript


Form

Normally to use button you need <form> which sends request to Flask to url defined in action="..." and Flask sends back response (text/HTML) and browser automatically put it in window in place of previous HTML - so server has to generate full HTML again and again.

from flask import Flask, request, render_template_string
import datetime

app = Flask(__name__)

@app.route('/')
def index():
    return render_template_string('''<form action="/page" method="POST">
<button type="submit" name="btn" value="Button 1">Button 1</button>
<button type="submit" name="btn" value="Button 2">Button 2</button>
<button type="submit" name="btn" value="Button 3">Button 3</button>
</form>''')

@app.route('/page', methods=['GET', 'POST'])
def page():
    value = request.form.get('btn') # gives text from `value="Button 1"`
    return f'You pressed {value} at ' + datetime.datetime.now().strftime('%Y.%m.%d %H:%M.%S')

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

And the same using empty action="" so it sends request to the same url and it needs to check request.method to run different code

from flask import Flask, request, render_template_string
import datetime

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        value = request.form.get('btn') # gives text from `value="Button 1"`    
        info = f'You pressed {value} at ' + datetime.datetime.now().strftime('%Y.%m.%d %H:%M.%S')
    else:
        info = ""
    
    return render_template_string('''<form action="" method="POST">
<button type="submit" name="btn" value="Button 1">Button 1</button>
<button type="submit" name="btn" value="Button 2">Button 2</button>
<button type="submit" name="btn" value="Button 3">Button 3</button>
</form>{{text}}''', text=info)

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

JavaScript

If you want to execute Flask code without reloading all HTML then you need to use JavaScript which can send request to server using old XMLHttpRequest or modern fetch(), get response and replace only part of HTML. Often in this method server sends JSON data and JavaScript may use it to replace HTML in different places.

And this method need to learn JavaScript to create something more complex.

from flask import Flask, request, render_template_string
import datetime

app = Flask(__name__)

@app.route('/')
def index():
    return render_template_string('''
<button onclick="my_function()">Get Time</button>
<span id="time">Press Button to see current time on server.</span>

<script>
span_time = document.querySelector("#time");
function my_function(){
   fetch('/get_time')
   .then(res => res.text())
   .then(text => span_time.innerHTML = text);
}
</script>
''')

@app.route('/get_time')
def time():
    return datetime.datetime.now().strftime('%Y.%m.%d %H:%M.%S')

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

In examples I use render_template_string instead of render_template to make code simpler - now everyone can copy code and paste to one file and run it.

furas
  • 134,197
  • 12
  • 106
  • 148