Flask
Basic
生命周期
| 步骤 | 描述 | 
|---|---|
| 1 | 客户端(如浏览器)发起 HTTP 请求 | 
| 2 | WSGI 服务器(如 gunicorn、uWSGI)接收请求 | 
| 3 | 服务器将 HTTP 数据转换为 WSGI 环境字典(environ) | 
| 4 | 服务器调用 Flask 应用对象(即 WSGI callable) | 
| 5 | Flask 内部处理:路由匹配、调用视图函数、异常处理等 | 
| 6 | Flask 将视图函数的返回值封装为 WSGI 响应 | 
| 7 | WSGI 服务器将响应转换为 HTTP 响应并返回 | 
| 8 | 客户端接收响应并渲染页面 | 
浏览器
  │
  │ HTTP GET /hello/alice
  │
  ▼
WSGI 服务器
  │ environ, start_response
  │
  ▼
Flask.__call__
  │  ↓ 创建 RequestContext
  ▼
ctx.push()
  │  ↓ 绑定 request, session, g
  ▼
before_request 钩子
  │  ↓ 可以中断返回
  ▼
dispatch_request()
  │  ↓ 路由匹配 /hello/<name>
  ▼
hello(name='alice') 视图
  │  ↓ return 'Hello alice'
  ▼
make_response()
  │  ↓ str → Response
  ▼
after_request 钩子
  │  ↓ 可给响应加头
  ▼
session.save_session()
  │  ↓ Set-Cookie
  ▼
ctx.pop()
  │  ↓ teardown_request
  ▼
start_response(status, headers)
  │
  ▼
HTTP/1.1 200 OK
  │
浏览器 ◄--------响应体sequenceDiagram
    participant Client as 客户端
    participant Server as WSGI 服务器
    participant Flask as Flask 应用
    participant View as 视图函数
 
    Client->>Server: HTTP 请求
    Server->>Flask: 调用 app(environ, start_response)
    Flask->>Flask: 创建请求上下文
    Flask->>Flask: 路由匹配 (url_map)
    Flask->>View: 执行视图函数
    View->>Flask: 返回响应数据
    Flask->>Flask: 转换 Response 对象
    Flask->>Flask: 执行 after_request 钩子
    Flask->>Server: 返回响应
    Server->>Client: 发送 HTTP 响应
    Flask->>Flask: 销毁上下文←  Previous postPython类库Inspect
Next post  →Python类库Pandas

