What Flask Does
- Routing — decorator-based URL rules
- Templates — Jinja2 template engine
- Request/response — Werkzeug WSGI utilities
- Blueprints — modular application components
- Extensions — Flask-SQLAlchemy, Flask-Login, Flask-CORS, Flask-Migrate, Flask-RESTful
- CLI —
flask run, custom commands - Sessions — cookie-based, configurable
- Testing — built-in test client
- Context — application and request context management
- Signals — Blinker-based event system
Architecture
WSGI application. Request enters Werkzeug server, Flask routes it by matching URL rules (decorated functions). Request context is pushed per-request, providing access to request, g, session globals. Jinja2 renders HTML. Blueprints organize large apps into reusable modules.
Self-Hosting
# Production (never use flask run in prod)
pip install gunicorn
gunicorn app:app --bind 0.0.0.0:8000 --workers 4
# Docker
FROM python:3.12-slim
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD ["gunicorn", "app:app", "--bind", "0.0.0.0:8000"]Key Features
- Minimal core (~1500 lines)
- Decorator-based routing
- Jinja2 templates
- Werkzeug request/response
- Blueprints for modularity
- Extensive extension ecosystem
- Built-in debugger
- Test client
- CLI via Click
- Flask 3.0+ requires Python 3.8+
Comparison
| Framework | Type | Async | ORM |
|---|---|---|---|
| Flask | Micro | WSGI (sync) | Via extension |
| FastAPI | Async micro | ASGI | Via SQLAlchemy |
| Django | Full-stack | WSGI + ASGI | Built-in |
| Bottle | Micro | WSGI | None |
| Litestar | Async full | ASGI | Built-in |
常见问题 FAQ
Q: Flask vs FastAPI? A: FastAPI 原生 async、自带 OpenAPI 文档和 Pydantic 验证,适合现代 API;Flask 更简单、生态更老牌、教程更多。新纯 API 项目推荐 FastAPI,全栈或已有项目用 Flask 很好。
Q: Flask 支持 async 吗? A: Flask 2.0+ 支持 async views,但底层仍是 WSGI(在 threadpool 中跑 async)。真正的 async I/O 建议 FastAPI 或 Quart(Flask async 分支)。
Q: 怎么组织大型项目?
A: 用 Blueprints 按功能拆分模块。Application Factory 模式(create_app() 函数)支持不同环境配置。
来源与致谢 Sources
- Docs: https://flask.palletsprojects.com
- GitHub: https://github.com/pallets/flask
- License: BSD 3-Clause