Python Notes
Learn Flask, the lightweight Python web framework. Build your first web application, understand Flask
Flask is a lightweight, flexible Python web framework that gives you the tools to build web applications quickly and efficiently. Known as a "micro-framework," Flask doesn't include a database abstraction layer, form validation, or other features that third-party libraries provide — but it's incredibly easy to extend and learn.
Why Flask?
Flask is one of the most popular Python frameworks for several reasons:
- Minimal and Lightweight — No forced dependencies or project structure
- Flexible — Build anything from a simple API to a full web app
- Pythonic — Clean, readable code that follows Python conventions
- Extensive Ecosystem — Hundreds of Flask extensions available
- Great for APIs — Perfect for RESTful API development
- Excellent Documentation — One of the best-documented frameworks
Prerequisites
Before learning Flask, ensure you're comfortable with:
- Python 3.8+ basics (variables, functions, classes)
- Basic HTML/CSS knowledge
- Understanding of HTTP (GET, POST requests)
- Virtual environments and pip
Installation
Setting Up a Virtual Environment
Always use virtual environments to isolate your project dependencies:
# Create a new project directory
mkdir my-flask-app
cd my-flask-app
# Create a virtual environment
python -m venv venv
# Activate the virtual environment
# On Windows:
venv\Scripts\activate
# On macOS/Linux:
source venv/bin/activateInstalling Flask
pip install flaskVerify Installation
python -c "import flask; print(flask.__version__)"
# Output: 3.0.xFull Requirements File
# requirements.txt
flask>=3.0.0
python-dotenv>=1.0.0Install from requirements:
pip install -r requirements.txtYour First Flask Application
The Minimal App
Create a file called app.py:
from flask import Flask
# Create the Flask application instance
app = Flask(__name__)
# Define a route and view function
@app.route('/')
def hello_world():
return 'Hello, World!'
# Run the app
if __name__ == '__main__':
app.run(debug=True)Run your app:
python app.pyVisit http://127.0.0.1:5000 in your browser and you'll see "Hello, World!"
Understanding the Code
Let's break down each part:
from flask import FlaskThis imports the Flask class from the flask module.
app = Flask(__name__)Creates a Flask application instance. __name__ tells Flask the name of the module — this helps Flask find templates and static files.
@app.route('/')
def hello_world():
return 'Hello, World!'The @app.route('/') decorator tells Flask that when someone visits the root URL /, call the hello_world() function. This function returns the response to send back to the browser.
if __name__ == '__main__':
app.run(debug=True)Only runs the development server when the script is executed directly (not imported). debug=True enables the debugger and auto-reloader.
Flask Project Structure
For small projects, a single file works fine. For larger projects, use this structure:
Running Flask
Development Server
# Method 1: Run directly
python app.py
# Method 2: Using Flask CLI
flask --app app run
# Method 3: With debug mode enabled
flask --app app run --debug
# Method 4: Specify host and port
flask --app app run --host=0.0.0.0 --port=8080Environment Variables
# Set Flask environment variables
# Windows (Command Prompt):
set FLASK_APP=app.py
set FLASK_DEBUG=1
flask run
# Windows (PowerShell):
$env:FLASK_APP = "app.py"
$env:FLASK_DEBUG = "1"
flask run
# macOS/Linux:
export FLASK_APP=app.py
export FLASK_DEBUG=1
flask runUsing python-dotenv
Create a .env file:
Load it in your app:
Flask Configuration
Multiple Routes
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return '<h1>Home Page</h1>'
@app.route('/about')
def about():
return '<h1>About Page</h1><p>This is my Flask app.</p>'
@app.route('/contact')
def contact():
return '<h1>Contact Us</h1>'
@app.route('/services')
def services():
return '''
<h1>Our Services</h1>
<ul>
<li>Web Development</li>
<li>API Development</li>
<li>Consulting</li>
</ul>
'''
if __name__ == '__main__':
app.run(debug=True)Returning Different Responses
Flask can return various types of responses:
Flask Application Factory Pattern
For larger applications, use the Application Factory pattern:
# run.py
from app import create_app
app = create_app('development')
if __name__ == '__main__':
app.run()Flask Application Context
Flask uses application and request contexts to manage state:
from flask import Flask, g, current_app
app = Flask(__name__)
@app.before_request
def before_request():
"""Runs before every request."""
g.user = None # Initialize user as None
print("Before request hook called")
@app.after_request
def after_request(response):
"""Runs after every request."""
print(f"Response status: {response.status_code}")
return response
@app.teardown_request
def teardown_request(exception):
"""Runs at the end of each request."""
if exception:
print(f"Error occurred: {exception}")
@app.route('/context')
def context_demo():
# Access current app config
debug_mode = current_app.config.get('DEBUG')
return f'Debug mode: {debug_mode}'Error Handling
from flask import Flask, render_template, jsonify
app = Flask(__name__)
@app.errorhandler(404)
def not_found(error):
return jsonify({'error': 'Page not found', 'status': 404}), 404
@app.errorhandler(500)
def internal_error(error):
return jsonify({'error': 'Internal server error', 'status': 500}), 500
@app.errorhandler(403)
def forbidden(error):
return jsonify({'error': 'Forbidden', 'status': 403}), 403
# Custom exception
class APIError(Exception):
def __init__(self, message, status_code=400):
self.message = message
self.status_code = status_code
@app.errorhandler(APIError)
def handle_api_error(error):
return jsonify({'error': error.message}), error.status_code
@app.route('/test-error')
def test_error():
raise APIError('Something went wrong', 400)Practice Exercises
Exercise 1: Personal Portfolio App
Create a Flask app with the following routes:
/— Home page with your name and a brief introduction/projects— List of your projects/skills— Your technical skills/contact— Contact information
Exercise 2: Mini Calculator API
Build a Flask API that accepts two numbers and an operation:
/add?a=5&b=3— Returns{"result": 8}/subtract?a=10&b=4— Returns{"result": 6}/multiply?a=3&b=7— Returns{"result": 21}/divide?a=15&b=3— Returns{"result": 5.0}
Exercise 3: Configuration Practice
Create a Flask app that:
- Reads configuration from a
.envfile - Uses the Application Factory pattern
- Has separate
DevelopmentConfigandProductionConfigclasses - Prints the active config name on startup
Summary
In this lesson, you learned:
- ✅ What Flask is and why it's popular
- ✅ How to install Flask and set up a virtual environment
- ✅ Creating your first Flask application
- ✅ Understanding routes and view functions
- ✅ Organizing a Flask project structure
- ✅ Running the development server
- ✅ Working with Flask configuration
- ✅ Using the Application Factory pattern
- ✅ Basic error handling
Next Steps
- Flask Routing — Learn about dynamic URLs, URL converters, and HTTP methods
- Flask Templates — Use Jinja2 to create dynamic HTML pages
- Flask Forms — Handle user input with WTForms
- Flask Database — Connect to SQLite/PostgreSQL with SQLAlchemy
*Next Lesson: Flask Routing →*
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Introduction to Flask.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Python Master Course topic.
Search Terms
python-master-course, python master course, python, master, course, web, development, flask
Related Python Master Course Topics