nimbuscode.dev/technologies/flask
C:\> cat TECHNOLOGIES/FLASK.md
Loading Flask documentation...

Flask

Python Microframework

1. Introduction

Flask is a lightweight, micro web framework for Python that is designed to make getting started with web development quick and easy, with the ability to scale up to complex applications. Created in 2010 by Armin Ronacher as an April Fool's joke that evolved into a legitimate project, Flask has become one of the most popular Python web frameworks due to its simplicity and flexibility.

Unlike more comprehensive frameworks like Django, Flask follows a "micro" philosophy, providing only the core components needed for web development while allowing developers to choose the tools and libraries they want to use for other functionality like database access, form validation, and authentication.

2. Syntax Examples

Basic Flask Application
from flask import Flask, render_template

app = Flask(__name__)

# Route for the home page
@app.route('/')
def home():
    return 'Hello, World!'

# Route with variable rules
@app.route('/user/<username>')
def show_user_profile(username):
    return f'User: {username}'

# Using templates
@app.route('/greeting/<name>')
def greeting(name):
    return render_template('greeting.html', name=name)

if __name__ == '__main__':
    app.run(debug=True)
HTTP Methods and Forms
from flask import Flask, request, redirect, url_for

app = Flask(__name__)

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        
        # Validate credentials (simplified example)
        if username == 'admin' and password == 'secret':
            return redirect(url_for('dashboard'))
        else:
            return 'Invalid credentials!'
    
    # If GET request, show the login form
    return '''
        <form method="post">
            <label>Username: <input type="text" name="username"></label><br>
            <label>Password: <input type="password" name="password"></label><br>
            <input type="submit" value="Login">
        </form>
    '''
Blueprints and Application Structure
# blueprint_example/auth.py
from flask import Blueprint, render_template, redirect, url_for

auth = Blueprint('auth', __name__)

@auth.route('/login')
def login():
    return render_template('auth/login.html')

@auth.route('/register')
def register():
    return render_template('auth/register.html')

@auth.route('/logout')
def logout():
    # Logic to log user out
    return redirect(url_for('main.index'))

# blueprint_example/app.py
from flask import Flask
from .auth import auth

app = Flask(__name__)
app.register_blueprint(auth, url_prefix='/auth')

@app.route('/')
def index():
    return 'Welcome to the main page!'
RESTful API with Flask
from flask import Flask, jsonify, request

app = Flask(__name__)

# Sample data
tasks = [
    {
        'id': 1,
        'title': 'Learn Flask',
        'description': 'Find resources and complete tutorials',
        'done': False
    },
    {
        'id': 2,
        'title': 'Build an API',
        'description': 'Create a RESTful API with Flask',
        'done': False
    }
]

# Get all tasks
@app.route('/api/tasks', methods=['GET'])
def get_tasks():
    return jsonify({'tasks': tasks})

# Get a single task
@app.route('/api/tasks/<int:task_id>', methods=['GET'])
def get_task(task_id):
    task = [task for task in tasks if task['id'] == task_id]
    if len(task) == 0:
        return jsonify({'error': 'Not found'}), 404
    return jsonify({'task': task[0]})

# Create a new task
@app.route('/api/tasks', methods=['POST'])
def create_task():
    if not request.json or not 'title' in request.json:
        return jsonify({'error': 'Missing title field'}), 400
        
    task = {
        'id': tasks[-1]['id'] + 1 if tasks else 1,
        'title': request.json['title'],
        'description': request.json.get('description', ""),
        'done': False
    }
    tasks.append(task)
    return jsonify({'task': task}), 201

3. Main Uses

Flask is primarily used for:

  • RESTful API development
  • Small to medium web applications
  • Prototyping and MVP development
  • Microservices
  • Static websites
  • Backend for SPAs (Single Page Applications)
  • Educational purposes and learning web development

4. Pros and Cons

Advantages

  • Lightweight and minimalist design
  • Easy to learn and get started with
  • Flexible and unopinionated architecture
  • Great for small projects and APIs
  • Built-in development server and debugger
  • Extensive documentation and community support
  • Compatible with various extensions

Limitations

  • No built-in database abstraction layer
  • No built-in form validation or authentication
  • Can require more setup work for large applications
  • Limited built-in security features compared to frameworks like Django
  • Less structured approach might lead to inconsistent code organization

5. History & Evolution

Major milestones in Flask's development:

  • 2010 - Initial release by Armin Ronacher (originally started as an April Fool's joke)
  • 2011 - Flask 0.7 released with significant improvements
  • 2013 - Flask 0.10 with enhanced compatibility
  • 2017 - Flask 0.12 with improved documentation
  • 2018 - Flask 1.0 released, marking a stable API
  • 2020 - Flask 2.0 with async support and improved typing
  • 2022 - Flask 2.2 with enhanced Python compatibility

Flask has maintained its philosophy of simplicity while evolving to accommodate modern Python features and web development practices.

6. Learning Resources

Here are some excellent resources for learning Flask:

7. Related Technologies

Technologies often used with Flask or alternative options:

C:\> cd ../