fro flask import Flask, request, render_template, url_for, redirect, session

from flask import Flask, request, render_template, url_for, redirect, session
  1. from flask import Flask: Imports the Flask class from the Flask framework, which is used to create a Flask web application.

  2. request: Imports the request object from Flask, which allows access to incoming request data such as form submissions or query parameters.

  3. render_template: Imports the render_template function from Flask, which is used to render HTML templates for the web application.

  4. url_for: Imports the url_for function from Flask, which is used to generate URLs for the specified endpoint.

  5. redirect: Imports the redirect function from Flask, which is used to redirect the user to a different endpoint or URL.

  6. session: Imports the session object from Flask, which is used to store and retrieve session data across requests.

app = Flask(__name__)
  1. 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.
def index():
    return render_template('index.html')
  1. @app.route('/'): Decorates the index function to be the handler for the root URL ("/") of the web application.

  2. def index():: Defines the index function, which will be executed when a request is made to the root URL.

  3. 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'))
        return redirect(url_for('index'))
  1. @app.route('/submit', methods=['POST']): Decorates the submit function to be the handler for the "/submit" URL with the HTTP method set to POST.

  2. def submit():: Defines the submit function, which handles form submissions.

  3. if request.method == 'POST':: Checks if the incoming request is a POST request.

  4. data = request.form['data']: Retrieves the value of the form field named "data" from the submitted form.

  5. session['data'] = data: Stores the retrieved data in the session for future use.

  6. return redirect(url_for('index')): Redirects the user back to the root URL after form submission.

  7. else:: Handles cases where the request method is not POST, redirecting to the root URL.

if __name__ == '__main__':
  1. if __name__ == '__main__':: Checks if the script is being run directly (not imported as a module).

  2. 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).