# RuntimeError: 当前请求无法使用会话。

- **ID:** `python/flask-runtimeerror-session-not-available`
- **领域:** python
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

在请求上下文之外或初始化之前访问会话。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 3.x | active | — | — |

## 解决方案

1. **Ensure request context is active** (90% 成功率)
   ```
   with app.test_request_context():
    session['key'] = 'value'
    print(session['key'])
   ```
2. **Initialize session in route** (95% 成功率)
   ```
   @app.route('/login')
def login():
    session['user'] = 'Alice'
    return 'Logged in'
   ```

## 无效尝试

- **Setting secret_key after session access** — Secret key must be set before first session use. (75% 失败率)
- **Using flask.session without import** — Session object not available without import. (60% 失败率)
