Flask

A micro web framework for Python

Flask Overview

Flask is a lightweight WSGI web application framework in Python. It is designed to make getting started quick and easy, with the ability to scale up to complex applications. It began as a simple wrapper around Werkzeug and Jinja and has become one of the most popular Python web application frameworks.

Initial release

April 2010

Stable release

2.3.2 (May 2023)

Written in

Python

License

BSD License

Key Features

Common Use Cases

Microservices

Small, focused services in a larger system.

Prototyping

Quickly build proof-of-concept apps.

REST APIs

Backend services for web/mobile apps.

Simple Web Apps

When full-stack frameworks are overkill.

Example Code

# Basic Flask application
from flask import Flask, render_template, request, jsonify

app = Flask(__name__)

@app.route('/')
def home():
    return 'Hello, World!'

@app.route('/greet/<name>')
def greet(name):
    return f'Hello, {name}!'

@app.route('/api/data', methods=['GET', 'POST'])
def api_data():
    if request.method == 'POST':
        data = request.get_json()
        return jsonify({'received': data})
    return jsonify({'message': 'Send a POST request with JSON data'})

@app.route('/template')
def template_example():
    return render_template('example.html', title='Flask Template')

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

# Flask with SQLAlchemy example
"""
from flask_sqlalchemy import SQLAlchemy

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///example.db'
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)

    def __repr__(self):
        return f'<User {self.username}>'

@app.route('/users')
def users():
    users = User.query.all()
    return render_template('users.html', users=users)
"""

# Flask template example (HTML)
"""
<!-- templates/example.html -->
<!DOCTYPE html>
<html>
<head>
    <title>{{ title }}</title>
</head>
<body>
    <h1>{{ title }}</h1>
    <p>This is a Flask template example.</p>
</body>
</html>
"""

Learning Resources