Sanic Middleware 中间件

Translate from sanic docs

Middleware

Middleware are functions which are executed before or after requests to the server. They can be used to modify the request to or response from user-defined handler functions.

中间件是在服务器请求运行前或运行后执行的函数,其被用来调整 请求or响应(从用户自定义函数中)

There are two types of middleware: request and response. Both are declared using the @app.middleware decorator, with the decorator’s parameter being a string representing its type: request or response. Response middleware receives both the request and the response as arguments.

有 request 和 response 两种中间件,均通过@app.middleware装饰器声明,装饰器的参数是字符串,类型有 request,response 。response中间件同时接收 request 和 response 参数。

The simplest middleware doesn’t modify the request or response at all:

最简单的中间件,未修改 request, response

@app.middleware('request')
async def print_on_request(request):
    print("I print when a request is received by the server")

@app.middleware('response')
async def print_on_response(request, response):
    print("I print when a response is returned by the server")

Modifying the request or response

Middleware can modify the request or response parameter it is given, as long as it does not return it. The following example shows a practical use-case for this.

中间件可以修改给定的 request 和 response 参数,前提是中间件不返回这些参数。下面的程序提供了一个可行的例子:

app = Sanic(__name__)

@app.middleware('response')
async def custom_banner(request, response):
    response.headers["Server"] = "Fake-Server"

@app.middleware('response')
async def prevent_xss(request, response):
    response.headers["x-xss-protection"] = "1; mode=block"

app.run(host="0.0.0.0", port=8000)

The above code will apply the two middleware in order. First, the middleware custom_banner will change the HTTP response header Server to Fake-Server, and the second middleware prevent_xss will add the HTTP header for preventing Cross-Site-Scripting (XSS) attacks. These two functions are invoked after a user function returns a response.

上面的代码依次运行了两个中间件。第一个中间件 custom_banner 修改 HTTP Response hand server 为 Fake-server。第二个中间件 prevent_xss 将添加 HTTP header 以抵挡 XSS 攻击。 这两个函数在用户函数返回响应后被激活。

Responding early

If middleware returns a HTTPResponse object, the request will stop processing and the response will be returned. If this occurs to a request before the relevant user route handler is reached, the handler will never be called. Returning a response will also prevent any further middleware from running.

如果中间件返回 HTTPResponse 对象, request会停止运行并且 response 会被返回。如果上述情况出现早与相应的路由处理程序被触发, 那么这个处理器永远也不会被运行。返回 response可以保护其他运行中的中间件。

@app.middleware('request')
async def halt_request(request):
    return text('I halted the request')

@app.middleware('response')
async def halt_response(request, response):
    return text('I halted the response')

你可能感兴趣的:(Sanic Middleware 中间件)