Quiz 2

Advanced Flask/Backend: Blueprints, Error Handlers, Middleware, Async Tasks

412 words
2 min read
Python Week 1: the first filter for runtime behavior
Visual companion
Python
Type and operator map

Python Week 1: the first filter for runtime behavior

View
Revision summary

What this note is really saying

Short form

# Advanced Flask/Backend: Blueprints, Error Handlers, Middleware, Async Tasks ## 🎯 Learning Objectives - Structure Flask applications with Blueprints for modularity - Implement custom error handlers and middleware - Use Celery for background task processing - Design RESTful APIs following best practices ## 📖 Core...

Advanced Flask/Backend: Blueprints, Error Handlers, Middleware, Async Tasks

🎯 Learning Objectives

  • Structure Flask applications with Blueprints for modularity
  • Implement custom error handlers and middleware
  • Use Celery for background task processing
  • Design RESTful APIs following best practices

📖 Core Content

1.1 Flask Blueprints

python
# runnable
from flask import Blueprint, jsonify
# Define blueprint
auth_bp = Blueprint('auth', __name__, url_prefix='/auth')
@auth_bp.route('/login', methods=['POST'])
def login():
    return jsonify({"message": "Login endpoint"})
@auth_bp.route('/register', methods=['POST'])
def register():
    return jsonify({"message": "Register endpoint"})
# Register in main app
# from flask import Flask
# app = Flask(__name__)
# app.register_blueprint(auth_bp)

1.2 Error Handlers

python
# runnable
from flask import jsonify
# Custom error handler
@app.errorhandler(404)
def not_found(error):
    return jsonify({
        "error": "Not Found",
        "message": "The requested resource was not found",
        "status_code": 404
    }), 404
@app.errorhandler(500)
def internal_error(error):
    return jsonify({
        "error": "Internal Server Error",
        "message": "An unexpected error occurred",
        "status_code": 500
    }), 500

1.3 Async Tasks with Celery

python
# runnable
from celery import Celery
celery = Celery('tasks', broker='redis://localhost:6379/0')
@celery.task
def process_image(image_path):
    """Background image processing - runs asynchronously."""
    # Heavy processing here
    result = {"status": "processed", "path": image_path}
    return result
# Trigger async task from Flask
# @app.route('/upload', methods=['POST'])
# def upload():
#     task = process_image.delay(file_path)
#     return jsonify({"task_id": task.id}), 202

1.4 Why This Matters

Production Flask apps need more than a simple script. Blueprints keep the code organized as the app grows. Error handlers provide consistent API responses. Background tasks prevent blocking the web server on long operations.

2. 📝 Practice Questions

Q1: Your Flask app has become a single file with 2000+ lines. Name three refactoring steps to improve maintainability.
  1. Split into Blueprints: Create separate blueprints for auth, API, admin, etc. Each in its own file.
  2. Extract models to separate module: Move all SQLAlchemy models to models.py.
  3. Configuration in a separate file: Use config.py or environment variables for settings.
  4. Services layer: Move business logic out of route handlers into service classes.
  5. Celery tasks in a separate module: All async tasks in tasks.py.
This creates a structure like:
pseudo
app/
├── __init__.py       # App factory
├── config.py         # Configuration
├── models.py         # Database models
├── auth/             # Auth blueprint
├── api/              # API blueprint
├── tasks.py          # Celery tasks
└── utils.py          # Helper functions
Document outline

Keep your place and jump directly to a heading.

Table of Contents
System Normal // Awaiting Context

Intelligence Hub

Navigate the knowledge graph to generate context. The Hub adapts dynamically to surface backlinks, related notes, and metadata insights.