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.
中間件是在服務(wù)器請(qǐng)求運(yùn)行前或運(yùn)行后執(zhí)行的函數(shù),其被用來(lái)調(diào)整 請(qǐng)求or響應(yīng)(從用戶自定義函數(shù)中)
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
orresponse
. Response middleware receives both the request and the response as arguments.
有 request 和 response 兩種中間件贷帮,均通過(guò)@app.middleware
裝飾器聲明,裝飾器的參數(shù)是字符串蜀铲,類型有 request,response
。response中間件同時(shí)接收 request 和 response 參數(shù)票唆。
The simplest middleware doesn’t modify the request or response at all:
最簡(jiǎn)單的中間件夺刑,未修改 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 參數(shù),前提是中間件不返回這些參數(shù)唆铐。下面的程序提供了一個(gè)可行的例子:
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.
上面的代碼依次運(yùn)行了兩個(gè)中間件。第一個(gè)中間件 custom_banner
修改 HTTP Response hand server 為 Fake-server奔滑。第二個(gè)中間件 prevent_xss
將添加 HTTP header 以抵擋 XSS 攻擊艾岂。 這兩個(gè)函數(shù)在用戶函數(shù)返回響應(yīng)后被激活。
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
對(duì)象朋其, request
會(huì)停止運(yùn)行并且 response
會(huì)被返回王浴。如果上述情況出現(xiàn)早與相應(yīng)的路由處理程序被觸發(fā), 那么這個(gè)處理器永遠(yuǎn)也不會(huì)被運(yùn)行梅猿。返回 response
可以保護(hù)其他運(yùn)行中的中間件氓辣。
@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')