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:
- Import necessary modules:
Flask
: to create the web application.render_template
: to render HTML templates.request
: to handle HTTP requests.Initialize the Flask application:
app = Flask(__name__)
: Create an instance of the Flask class.Define the route for the root URL
'/'
:@app.route('/')
: Decorator that binds the URL endpoint'/'
to theindex()
function.def index():
: Define theindex
function to render theindex.html
template.Define the route for form submission:
@app.route('/submit', methods=['POST'])
: Decorator that binds the URL endpoint'/submit'
to thesubmit()
function and specifies that it only accepts POST requests.def submit():
: Define thesubmit
function to handle form submission.Check the request method and retrieve form data:
if request.method == 'POST':
: Check if the request method is POST.button_value = request.form['button']
: Get the value of the form field named'button'
from the submitted form.Process the button value:
if button_value == 'Click Me':
: Check the value of the button submitted.message = "Button Clicked!"
: If the button value is'Click Me'
, setmessage
to "Button Clicked!".else: message = "Unknown Button"
: If the button value is not'Click Me'
, setmessage
to "Unknown Button".Return the response:
return message
: Return the message based on the button clicked or an unknown button.return 'Invalid request'
: If the request method is not POST, return an "Invalid request" message.Run the Flask application:
if __name__ == '__main__':
: Check if the script is executed directly.app.run(debug=True)
: Start the Flask application in debug mode.