Flask
Flask is a lightweight Python web framework that gives you the essentials for web development without enforcing a project structure. This flexibility makes...
Building Web Apps with Flask
Flask is a lightweight Python web framework that gives you the essentials for web development without enforcing a project structure. This flexibility makes it ideal for small-to-medium applications, microservices, and REST APIs.
Install with pip install flask. A minimal Flask application: from flask import Flask app = Flask(__name__)
@app.route('/') def home(): return 'Hello, World!'
if __name__ == '__main__': app.run(debug=True)
Run with python app.py. Flask automatically restarts when you save changes (debug=True).
URL routing with variable parts: @app.route('/user/<int:user_id>') def get_user(user_id): return f'User ID: {user_id}'
HTTP methods: @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] # authenticate...
The request object gives access to form data (request.form), query parameters (request.args), JSON body (request.get_json()), and uploaded files (request.files).
Flask templates use Jinja2. Render a template: from flask import render_template @app.route('/profile/<name>') def profile(name): return render_template('profile.html', username=name)
Blueprints organize large applications into modules: from flask import Blueprint auth = Blueprint('auth', __name__, url_prefix='/auth')
@auth.route('/register') def register(): return 'Register page'
# In main app: app.register_blueprint(auth)
Flask-SQLAlchemy integrates database access: pip install flask-sqlalchemy. Flask-Login handles user sessions. Flask-WTF provides form validation with CSRF protection.
Application configuration via environment: app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY') app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL')
Practical tip: Organize Flask apps using the Application Factory pattern (create_app() function) and Blueprints from the start, even for small projects. Retrofitting structure into a monolithic app.py is painful.
Exam tip: Flask's debug mode (debug=True) must NEVER be used in production. It exposes an interactive debugger in the browser that allows arbitrary code execution, which is a critical security vulnerability.