shared_ctx

 

2023-03-19

shared_ctx 类似于 ctx,可以在应用程序的整个生命周期内共享状态,不同的是 shared_ctx 可以在多个 Sanic 进程之间共享数据,以及不支持常规对象,如 str, int, dict, list 等,不过正常可以通过使用 multiprocessing 的一些方法达到类似需求。

创建共享对象的前提是在主进程 listeners#main_process_start 中加载:

1
from multiprocessing import Manager
2
3
# 先在主进程中加载
4
@app.main_process_start
5
async def main_process_start(app):
6
app.shared_ctx.persons = Manager().dict("num": 42)
7
8
# 之后就可以调用或修改
9
@app.route("/name")
10
async def main(request, name):
11
app.shared_ctx.persons["name"] = name
12
return json(dict(app.shared_ctx.persons))
13
14
@app.route("/my")
15
async def main(request, name):
16
return json(dict(app.shared_ctx.persons))

参考