Flask is a “micro” web framework, meaning it’s lightweight and easy to get started with, but it can scale to very complex applications. Using it essentially involves creating a Python script that “routes” specific web addresses (URLs) to Python functions.
1. Installation
First, ensure you have Flask installed via pip:
pip install flask
2. Create Your First App
Create a file named app.py. This is the skeleton of a basic Flask application:
from flask import Flask
# Initialize the Flask application
app = Flask(__name__)
# Define a "route" (the URL path)
@app.route("/")
def home():
return "<h1>Hello, Flask!</h1>"
# Run the app if this file is executed directly
if __name__ == "__main__":
app.run(debug=True)
3. Running the Server
In your terminal, run the script:
python app.py
You will see an output like Running on [http://127.0.0.1:5000](http://127.0.0.1:5000). Open that link in your browser, and you’ll see “Hello, Flask!”.
4. Key Concepts to Understand
Routing & Dynamic URLs
You can map different URLs to different functions. You can also capture parts of the URL as variables:
@app.route("/user/<name>")
def greet(name):
return f"Hello, {name}!"
Rendering HTML (Templates)
Instead of returning raw strings, you usually want to return full HTML files. Flask uses the Jinja2 engine for this.
- Create a folder named
templates. - Inside it, create
index.html. - Use
render_templatein your Python file:
from flask import render_template
@app.route("/")
def index():
return render_template("index.html", title="Home Page")
The Development Server (debug=True)
When you use debug=True, two things happen:
- Auto-Reload: The server restarts itself every time you save a change to your code.
- Debugger: If your code crashes, it provides an interactive error page in the browser to help you find the bug.
Summary Checklist
| Step | Action |
| 1 | Install Flask (pip install flask). |
| 2 | Create the Flask(__name__) instance. |
| 3 | Create functions with @app.route(). |
| 4 | Return a string or render_template(). |
| 5 | Run the app using app.run(). |
