create a flask app with a button in python

To create a Flask app with a button in Python, you need to follow these steps:

  1. Install Flask by running pip install Flask in your command prompt or terminal.
  2. Create a Python file with your Flask application code.
main.py
from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def home():
    if request.method == 'POST':
        # Here, you can write the code to handle the button click event.
        # For example, you can print a message to the console or update the database.
        print("Button clicked.")
    return render_template('home.html')

if __name__ == '__main__':
    app.run(debug=True)
444 chars
15 lines

Note that we have defined the / route and the home function, which renders the home.html file. Inside the function, we have checked whether the request method is POST. If it is POST, this means that the button has been clicked and we can execute the necessary code.

  1. Create a HTML file with the button.
<!DOCTYPE html>
<html>
<head>
    <title>Flask Button Example</title>
</head>
<body>
    <h1>Flask Button Example</h1>
    <form action="/" method="post">
        <input type="submit" value="Click me!">
    </form>
</body>
</html>
231 chars
13 lines

This HTML file contains a form with a button. Notice that the action attribute of the form is set to '/', which is the route that we defined in the Flask app. Also, the method attribute is set to 'post'.

  1. Create a CSS file (optional) to customize the button and the page.
body {
    background-color: #f0f0f0;
}

form {
    margin-top: 50px;
}

input[type="submit"] {
    padding: 10px 20px;
    background-color: #4CAF50;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
}
234 chars
17 lines

This CSS file is just an example. You can customize it to your liking.

  1. Run the Flask app by executing the Python file. Open your web browser and go to http://localhost:5000/ (assuming you have not changed the port number). Click the button and you should see the message "Button clicked." printed in the console.

related categories

gistlibby LogSnag