Understanding Your First Flask Application

Flask is a lightweight Python web framework used to build web applications and REST APIs. It provides the foundation for creating web pages, handling HTTP requests, and exposing API endpoints.


In this tutorial, we will create our very first Flask application that displays a simple "Hello World" message in a web browser.


Step 1: Import the Flask Class

from flask import Flask

The Flask class is imported from the flask module. This class is used to create our web application.

Step 2: Create the Flask Application

app = Flask(__name__)

Here, we create an instance of the Flask application.

  • app represents our web application.
  • __name__ tells Flask where the application is located so it can correctly find templates, static files, and other resources.

Step 3: Define a Route

@app.route('/')

The @app.route('/') decorator maps the root URL (/) of the website to a Python function.

Whenever a user opens:

http://localhost:5000/

Flask automatically calls the associated function.

Step 4: Create the View Function

def hello_world():
    return 'Hello World'

This function is executed whenever the root URL (/) is accessed. The string returned by the function becomes the HTTP response that is displayed in the browser.

Step 5: Start the Flask Development Server

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

This block ensures that the Flask development server starts only when the script is executed directly.

When app.run() is  is called, Flask starts a local web server (by default on http://127.0.0.1:5000). Opening this URL in a browser displays the message:



This is the code 
from flask import Flask      # Step 1: Import Flask class

app = Flask(__name__)        # Step 2: Create Flask app object

@app.route('/')              # Step 3: Define URL route
def hello_world():           # Step 4: Function for that route
    return 'Hello World'     # Step 5: What to display

if __name__ == '__main__':   # Step 6: Run only if directly executed
    app.run()                # Step 7: Start web server







Post a Comment

0 Comments