async 视图到底在哪里执行?请求上下文还在吗?视图返回后后台任务会怎样?全局的异步锁能用吗?这篇逐项验证 async 视图的边界。
sync 视图: {'main': True, 'thread': 'MainThread'}
async 视图: {'main': False, 'thread': 'ThreadPoolExecutor-1_0'}上一篇:Flask Async View;下一篇:同步代码阻塞异步请求。
app_name b contextvar set in before_request g_value set in before_request has_request_context True request_path /ctx session_x 1
create_task 之后立刻返回响应,1 秒后任务状态: not run await 了任务再返回: responded after task | 任务状态: finished
GET /global-event → 200 'timed out waiting (event not set)' GET /global-event → 500 '<!doctype html>\n<html lang=en>\n<title>500 Internal Server Error</title' GET /global-lock → 200 'lock ok' GET /global-lock → 500 '<!doctype html>\n<html lang=en>\n<title>500 Internal Server Error</title' 再请求一次 /global-event(让异常传播出来)→ RuntimeError: <asyncio.locks.Event object at 0x108b22660 [unset]> is bound to a different event loop 再请求一次 /global-lock(让异常传播出来)→ RuntimeError: <asyncio.locks.Lock object at 0x108b227b0 [locked]> is bound to a different event loop
asyncio.to_thread 里直接 has_request_context(): True 再用 copy_current_request_context 包装后读 request.path: /copy-ctx 自己 new 的 threading.Thread 里 has_request_context(): False to_thread 的工作线程名: asyncio_0