Category
Flask 本番運用ガイド(アプリケーションファクトリ/Blueprint/Flask-SQLAlchemy・Migrate/認証・JWT/Celery非同期/REST API・OpenAPI/キャッシュ・レート制限/テスト/デプロイ/セキュリティ/可観測性/技術選定)の実装記事群
Flask は『核(ルーティング・リクエスト/レスポンス・テンプレート・設定・コンテキスト)だけを提供し、ORM・フォーム検証・管理画面は内蔵しない』という設計思想の WSGI マイクロフレームワークです。だからこそ本番品質は、機能ではなく『構造設計』で決まります。本クラスタは、グローバル app を捨てる create_app のアプリケーションファクトリと Blueprint・init_app による大規模構成、import 時に存在しない app を current_app / g で引き回さないコンテキスト設計、test_client と pytest fixtures による境界の契約テスト、開発サーバーを捨て Gunicorn・ProxyFix・Docker で動かす本番デプロイ、署名 Cookie セッション・SECRET_KEY・CSRF(Flask-WTF)・自動エスケープのセキュリティ、errorhandler の JSON エラーと dictConfig 構造化ログ・リクエスト ID の可観測性、そして Flask を採用すべきか(FastAPI / Django との比較)という上流の技術選定までを扱います。さらに案件で必ず問われる実装——Flask-SQLAlchemy(2.0スタイル)+ Flask-Migrate のデータ層、Flask-Login(セッション)/ Flask-JWT-Extended(トークン)の認証、Celery × Redis の冪等な非同期タスク、MethodView による REST API 設計と Flask-smorest による OpenAPI / Swagger の自動生成、Flask-Caching / Flask-Limiter による性能最適化とレート制限——まで、拡張エコシステムを本番品質で組み合わせる設計を網羅します。経済産業大臣賞を受賞した B2B SaaS のバックエンドを Flask / SQLAlchemy / PostgreSQL で設計・実装し本番運用した知見を根拠に、設計の自由を負債にしないための規律を、各公式ドキュメントに忠実な実コードで体系化します。境界バリデーション(marshmallow)は『marshmallow』クラスタ、SQLAlchemy 本体・Alembic は『Pythonバックエンド』クラスタを参照してください。
14 articles in total
Foundational guide
Foundational guide (start here)
Flask Production Operations Guide (3.1 Series): The Overall Picture of Application Factory, Blueprints, Configuration, Context, and Production Deployment
An overall guide to designing and operating Flask 3.1 series at production quality. We systematize — in real code faithful to the latest official documentation — the philosophy of the WSGI microframework, the create_app application factory, splitting with Blueprints, configuration management with from_prefixed_env and the instance folder, the current_app/g context, extensions' init_app, error handling and logging, SECRET_KEY and safe Cookies, production deployment with Gunicorn + ProxyFix, and testing with pytest.
Related practical articles
- PythonFlask認証JWTセキュリティ
A Guide to Implementing Authentication in Flask: When to Use Flask-Login (Session Auth) vs. Flask-JWT-Extended (Token Auth), and How to Build Both for Production
A production-quality guide to Flask authentication. From the decision axis for choosing between Flask-Login (0.6.3) session auth and Flask-JWT-Extended (4.7.4) token (JWT) auth per client type, through register/login/logout, @login_required, current_user, refresh tokens, blocklists, and httpOnly Cookie + CSRF — explained with real code faithful to the official docs. It also honestly maps out the boundary between rolling your own auth and using a managed IdP.
30 min read - PythonFlaskCeleryRedis非同期処理
Flask × Celery × Redis: Running Background Tasks and Job Queues at Production Quality (Flask Context Integration, Idempotency, Resilience)
A practical guide to designing async tasks / job queues at production quality with Flask Celery Redis. From the official celery_init_app and FlaskTask app-context integration, shared_task, .delay/AsyncResult, idempotency that withstands at-least-once delivery, the resilience of autoretry/acks_late/visibility timeout, Celery Beat's periodic execution, to a Docker setup that runs workers in a separate container plus Flower monitoring and task_id–correlated logs — explained with real code faithful to the latest Flask official docs and Celery documentation.
23 min read - PythonFlaskOpenAPISwaggerREST API
Auto-Generating OpenAPI/Swagger in Flask: Building Schema-Driven REST APIs and API Docs at Production Quality with Flask-smorest
An implementation guide to auto-generating OpenAPI/Swagger with Flask-smorest 0.47. Bundle Flask + marshmallow + webargs + apispec to simultaneously generate input validation, response shaping, and the OpenAPI spec from a single schema. @blp.arguments/@blp.response, Swagger UI/ReDoc, pagination, error documentation, protecting Swagger UI in production, and generating openapi.json in CI — explained with real code.
23 min read - PythonFlaskパフォーマンスRedisレート制限
Flask Performance Optimization in Practice: Caching with Flask-Caching (Redis), Rate Limiting with Flask-Limiter, and N+1 and Connection Pools
An implementation guide to Flask performance optimization and cost reduction. Measurement-first (p95/p99), Flask-Caching 2.4.0's Redis cache (@cache.cached/@cache.memoize, invalidation), Flask-Limiter's rate limiting and the must-have-shared-Redis trap, and N+1, connection pools, and PgBouncer—all explained with official-compliant real code.
28 min read - PythonFlaskREST APIMethodViewBlueprint
REST API Design in Flask: MethodView (Class-Based Views), Resource Design with Blueprints, API Versioning, Pagination, and HTTP Semantics
A practical guide to designing a production-quality REST API in the Flask 3.1 line. From MethodView's item/collection two-class structure, as_view+add_url_rule and the register_api factory, resource splitting and /api/v1 versioning with Blueprints, HTTP semantics (idempotency, status codes), to conventions for pagination/filtering and the JSON error envelope — explained with real code faithful to the official docs.
31 min read - PythonFlaskSQLAlchemyFlask-Migrateデータベース
Flask's Data Layer: Designing and Operating a Production DB with Flask-SQLAlchemy 3.x (2.0 Style) and Flask-Migrate
A practical guide to designing and operating Flask SQLAlchemy Migrate at production quality. Explained with real code faithful to the official documentation: Flask-SQLAlchemy 3.1 and SQLAlchemy 2.0's typed Mapped/mapped_column, the 2.0 query session.execute(select), get_or_404・db.paginate, the application context and per-request sessions, the SQLALCHEMY_ENGINE_OPTIONS pool_pre_ping/pool_recycle pool design, the read-replica of SQLALCHEMY_BINDS, and Flask-Migrate (Alembic)'s autogenerate review discipline and CI/CD upgrade.
23 min read - PythonFlaskBlueprintアーキテクチャ設計本番運用
Flask Large-App Structure: Extending Without Circular Imports Using the Application Factory (create_app) and Blueprints
A practical guide for designing a large Flask 3.1-series app structure at production quality. Explained with real code faithful to the official documentation: the breakdown of the global app and circular imports, the create_app application factory, the bare extension → init_app of extensions.py, Blueprints' url_prefix / endpoint naming / nesting / templates and static files / error handlers / CLI, per-environment Config with from_object + from_prefixed_env, and the src/ layout and the YAGNI discipline of splitting.
22 min read - PythonFlaskアーキテクチャ設計本番運用バックエンド
A Thorough Explanation of Flask's Application Context and Request Context: Using current_app / g / request / session Correctly
An explanation of Flask 3.1's 2 contexts (application / request) faithful to the official spec. We systematize, in real code, the true nature of current_app, g, request, and session, the async-safe mechanism via contextvars + LocalProxy, teardown_appcontext, app_context/test_request_context, copy_current_request_context, and the correct handling of the Working outside of context error.
20 min read - PythonFlaskpytestテストバックエンド
Flask Testing Practical Guide: Writing Production-Quality Automated Tests with pytest fixtures, test_client, and test_cli_runner
A complete guide to writing Flask 3.1-series tests at production quality. Explained with real code faithful to the official documentation: why the application factory and test_client make testing easy, the effect of TESTING=True, the app/client/runner pytest-fixture trio, request verification with response.data/json/text, follow_redirects, and session_transaction, test_request_context and app_context, and CLI testing with test_cli_runner.
20 min read - PythonFlaskGunicornDockerWSGI
Flask Production Deployment in Practice: Gunicorn, Choosing a WSGI Server, ProxyFix, Docker, Graceful Shutdown
An implementation guide to deploying Flask 3.1.x at production quality. From why you abandon the development server, the separation of the WSGI app and the server, choosing among Gunicorn/Waitress/uWSGI/mod_wsgi, worker counts and gevent workers, the correct ProxyFix configuration and operating behind an ALB, multi-stage Docker and non-root containers, to graceful shutdown via SIGTERM and zero-downtime deploys on ECS — explained with real code faithful to the official documentation.
25 min read - PythonFlaskセキュリティCSRFCookie
Flask Security Implementation Guide (3.1 Series): Signed-Cookie Sessions, SECRET_KEY, Secure Cookies, CSRF, XSS Auto-Escaping, and Security Headers
An implementation guide for hardening Flask 3.1-series security boundaries at production quality. Explained with real code faithful to the official documentation: the true nature of the client-side signed-cookie session, SECRET_KEY and key rotation, SECURE/HttpOnly/SameSite secure cookies, Flask-WTF's CSRFProtect, Jinja's auto-escaping, HSTS/CSP/nosniff security headers, and DoS countermeasures.
25 min read - PythonFlask可観測性ロギングエラーハンドリング
Flask Error Handling, Logging, and Observability Guide (3.1 line): JSON Error Design, Structured Logs, Request IDs, Sentry, and Health Checks
Systematizing Flask 3.1-line production error handling and observability. From errorhandler/abort, custom HTTPException, and resolution order, HTTPException→JSON and a common error envelope, structured logs via dictConfig, request-ID correlation, Sentry integration and PII scrubbing, to ALB/ECS-oriented health checks—all explained with official-compliant real code.
23 min read - PythonFlaskFastAPIDjango技術選定
Flask vs. FastAPI vs. Django technology-selection guide: which to choose in which situation (2026 edition, production-operation decision axes)
A technology-selection guide comparing the differences of Flask, FastAPI, and Django from the viewpoint of production operation. It organizes architecture philosophy, sync/async, type validation, the admin screen, the learning curve, and current versions in a table, and shows the recommended framework by scenario — REST API, high-concurrency IO, instant admin screen, staged migration. The definitive guide to the Flask FastAPI Django difference, comparison, and selection.
17 min read