使用 SANIC 中间件,你需要在你的 SANIC 应用程序中定义一个中间件函数,并将其添加到应用程序的中间件列表中。
举个例子,假设你想要在每个请求的响应中添加一个自定义的头信息,你可以使用如下代码定义中间件函数:
from sanic import response
async def add_custom_header(request, response):
response.headers["X-Custom-Header"] = "MyCustomValue"
然后,你可以将这个中间件添加到应用程序的中间件列表中,如下所示:
from sanic import Sanicapp = Sanic()
app.middleware("response")(add_custom_header)
这样,在每个请求的响应中,都会添加一个名为 "X-Custom-Header" 的头信息,值为 "MyCustomValue"。
你也可以通过在路由装饰器上使用 middleware
参数来针对特定的接口使中间件生效。例如:
@app.route("/myroute", middleware=[add_custom_header])
async def myroute_handler(request):
# ...
这样,只有在访问 "/myroute" 接口时,中间件函数 add_custom_header
才会生效。