Concept Explanation
How do websites like Netflix, Instagram, or Pinterest actually work? At their core, they use a Web Framework—a set of tools that helps Python talk to the internet.
Flask is known as a "micro" framework. This doesn't mean it's small or weak; it means it is simple, flexible, and gives you total control. Unlike larger frameworks (like Django) that force you to do things their way, Flask lets you build your website exactly how you want. It's the perfect choice for beginners and for building fast, modern Web APIs.
How it works:
- A user types a URL in their browser (a "Request").
- Flask receives that request and looks at the URL (the "Route").
- Flask runs a specific Python function you wrote.
- That function returns HTML or data to the user's browser (the "Response").
Syntax or Core Structure
The Minimal Application
To start, you just need a few lines of code.
from flask import Flask
# Create the application object
app = Flask(__name__)
# Define a "Route" (the URL)
@app.route("/")
def home():
return "<h1>Welcome to my Flask Website!</h1>"
# Run the app
if __name__ == "__main__":
app.run(debug=True)
Routing with Variables
You can make your URLs dynamic!
@app.route("/user/<name>")
def greet(name):
return f"Hello, {name}! Welcome back."
Code Example #1 (Basic)
Creating a simple multi-page website.
from flask import Flask
app = Flask(__name__)
@app.route("/")
def index():
return "Home Page"
@app.route("/about")
def about():
return "About Page"
if __name__ == "__main__":
app.run()
Code Example #2 (Intermediate)
Returning JSON data for an API.
from flask import Flask, jsonify
app = Flask(__name__)
@app.route("/api/info")
def get_info():
data = {
"status": "online",
"version": "1.0.4",
"features": ["Login", "Search"]
}
return jsonify(data) # Converts the dict to a JSON response
if __name__ == "__main__":
app.run(debug=True)
Real World Example
A Simple Feedback Form: Imagine you want users to send you a message through your site.
from flask import Flask, request
app = Flask(__name__)
# This route only accepts "POST" requests (form submissions)
@app.route("/submit", methods=["POST"])
def submit_feedback():
# Get the data from the form
name = request.form.get("username")
message = request.form.get("feedback")
# In a real app, you'd save this to a database!
return f"Thank you {name}, we received your message: '{message}'"
if __name__ == "__main__":
app.run()
Common Mistakes
- Running as a Script: If you don't use
if __name__ == "__main__":, sometimes your app will try to start multiple times, causing errors. - Port Collisions: If another program is already using "Port 5000" (the default), Flask will crash. You can change it with
app.run(port=8080). - Returning Non-Strings: Flask functions MUST return a string, a tuple, or a Response object. If you try to return an integer (
return 1), Flask will crash.
Best Practices
- Enable Debug Mode: In development, use
app.run(debug=True). This reloads the server automatically when you save your code and shows you clear error messages in the browser. - Use Templates: Don't put huge blocks of HTML inside your Python file. Use the
render_template()function to load separate.htmlfiles. - Environment Variables: Instead of hardcoding secrets in your Flask app, use
.envfiles.
Practice Exercises
- The Calculator: Create a Flask route
/add/<a>/<b>that adds two numbers from the URL and returns the result. - The JSON Server: Create a simple "List of Books" as a Python list and return it as JSON when the user visits
/books. - The Hello Page: Create a route that takes a
colorin the URL and returns an HTML string with a background color matching that URL parameter.