Home > Software engineering >  how can I have a flask file wait for a specific button press in a html coded website? - python
how can I have a flask file wait for a specific button press in a html coded website? - python

Time:05-01

I would like to use flask to check when a button is pressed in an HTML coded website, the website will be up and running and the py app needs to be running too and wait for the button click, then on the button click, it will get the input content and print it. How do I do this?

this is my html code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>test</title>
</head>
<body>
    <input type="hallo"> 
    <button>Hallo</button>   
</body>
</html>

I have searched for a while but nothing I tried worked, please help. some code snippets would be great, thanks.

CodePudding user response:

Use a simple form that is submitted with a post request.
The value from the input field is queried using the name attribute.
The button of type submit submits the form.

from flask import (
    Flask, 
    render_template, 
    request
)

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        print(request.form.get('hallo'))
    return render_template('index.html')
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>test</title>
</head>
<body>
    <form method="post">
      <input type="text" name="hallo" /> 
      <button type="submit">Hallo</button>   
    </form>
</body>
</html>
  • Related