Python 框架 Sanic 应用上下文的使用

前记

初次接触 Sanic 框架,在使用的过程中,并没有在文档中发现如何使用应用上下文

使用

通过 issues 咨询后记录如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from sanic import Sanic
from sanic.response import text

app = Sanic('jakehu')

# 应用上下文
app.ctx.db = "msyql://..."

@app.get("/")
async def hello_world(request):
# 使用应用上下文
print(request.app.ctx)
return text("Hello, world.")

app.run(debug=True,auto_reload=True)

参考


题外话:
申明全局的 Json 序列化函数

1
2
from orjson import dumps
app = Sanic('jakehu', dumps=dumps)