Getting Started with Flask

Flask is a lightweight and popular Python web framework that makes it easy to build web applications. In this tutorial, we’ll guide you through setting up Flask and creating your first web app.

Step 1: Install Flask

Before starting, make sure you have Python installed on your system. Then install Flask using pip:

pip install flask

Step 2: Create a Basic Flask Application

Create a new Python file named app.py and add the following code:

from flask import Flask

    app = Flask(__name__)

    @app.route("/")
    def home():
        return "Hello, Flask!"

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

Step 3: Run Your Flask Application

Run your Flask app by executing the following command in your terminal:

python app.py

You should see output indicating the app is running on http://127.0.0.1:5000/. Open this URL in your browser to see the message Hello, Flask!.

Step 4: Add Routes

Flask allows you to define routes for different URLs. Update your app.py to include another route:

@app.route("/about")
    def about():
        return "This is the About Page."

Visit http://127.0.0.1:5000/about to see the new page.

Step 5: Rendering HTML Templates

Create a folder named templates, and inside it, create an index.html file:

<!DOCTYPE html>
    <html>
    <head>
        <title>Flask App</title>
    </head>
    <body>
        <h1>Welcome to Flask</h1>
    </body>
    </html>

Modify your app to render this template:

from flask import render_template

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

Step 6: Using Dynamic Content

You can pass data to your templates. Update your route like this:

@app.route("/")
    def home():
        name = "Flask Beginner"
        return render_template("index.html", name=name)

Update your index.html file to display the dynamic content:

<h1>Welcome, {{ name }}!</h1>

Next Steps

Explore Flask's additional features, such as handling forms, using a database, or deploying your app. Flask is highly flexible and perfect for both small projects and complex applications. Happy coding!