from flask import Flask, request, render_template, url_for, redirect, session
from flask import Flask
: Imports the Flask class from the Flask framework, which is used to create a Flask web application.
request
: Imports the request
object from Flask, which allows access to incoming request data such as form submissions or query parameters.
render_template
: Imports the render_template
function from Flask, which is used to render HTML templates for the web application.
url_for
: Imports the url_for
function from Flask, which is used to generate URLs for the specified endpoint.
redirect
: Imports the redirect
function from Flask, which is used to redirect the user to a different endpoint or URL.
session
: Imports the session
object from Flask, which is used to store and retrieve session data across requests.
app = Flask(__name__)
app = Flask(__name__)
: Creates an instance of the Flask class, representing the web application. The __name__
argument is a special variable in Python that represents the name of the current module. It is used by Flask to determine the root path of the application.
@app.route('/')
def index():
return render_template('index.html')
@app.route('/')
: Decorates the index
function to be the handler for the root URL ("/") of the web application.
def index():
: Defines the index
function, which will be executed when a request is made to the root URL.
return render_template('index.html')
: Renders the HTML template named "index.html" and returns it as the response for the root URL.
@app.route('/submit', methods=['POST'])
def submit():
if request.method == 'POST':
data = request.form['data']
session['data'] = data
return redirect(url_for('index'))
else:
return redirect(url_for('index'))
@app.route('/submit', methods=['POST'])
: Decorates the submit
function to be the handler for the "/submit" URL with the HTTP method set to POST.
def submit():
: Defines the submit
function, which handles form submissions.
if request.method == 'POST':
: Checks if the incoming request is a POST request.
data = request.form['data']
: Retrieves the value of the form field named "data" from the submitted form.
session['data'] = data
: Stores the retrieved data in the session for future use.
return redirect(url_for('index'))
: Redirects the user back to the root URL after form submission.
else:
: Handles cases where the request method is not POST, redirecting to the root URL.
if __name__ == '__main__':
app.run(debug=True)
if __name__ == '__main__':
: Checks if the script is being run directly (not imported as a module).
app.run(debug=True)
: Runs the Flask application in debug mode, making it convenient for development. The web server will listen for incoming requests on the default port (5000).