button in flask

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/submit', methods=['POST'])
def submit():
    if request.method == 'POST':
        button_value = request.form['button']
        if button_value == 'Click Me':
            message = "Button Clicked!"
        else:
            message = "Unknown Button"
        return message
    return 'Invalid request'

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

Explanation:

  1. Import necessary modules:
  2. Flask: to create the web application.
  3. render_template: to render HTML templates.
  4. request: to handle HTTP requests.

  5. Initialize the Flask application:

  6. app = Flask(__name__): Create an instance of the Flask class.

  7. Define the route for the root URL '/':

  8. @app.route('/'): Decorator that binds the URL endpoint '/' to the index() function.
  9. def index():: Define the index function to render the index.html template.

  10. Define the route for form submission:

  11. @app.route('/submit', methods=['POST']): Decorator that binds the URL endpoint '/submit' to the submit() function and specifies that it only accepts POST requests.
  12. def submit():: Define the submit function to handle form submission.

  13. Check the request method and retrieve form data:

  14. if request.method == 'POST':: Check if the request method is POST.
  15. button_value = request.form['button']: Get the value of the form field named 'button' from the submitted form.

  16. Process the button value:

  17. if button_value == 'Click Me':: Check the value of the button submitted.
  18. message = "Button Clicked!": If the button value is 'Click Me', set message to "Button Clicked!".
  19. else: message = "Unknown Button": If the button value is not 'Click Me', set message to "Unknown Button".

  20. Return the response:

  21. return message: Return the message based on the button clicked or an unknown button.
  22. return 'Invalid request': If the request method is not POST, return an "Invalid request" message.

  23. Run the Flask application:

  24. if __name__ == '__main__':: Check if the script is executed directly.
  25. app.run(debug=True): Start the Flask application in debug mode.