python middleware_Sanic middleware – 中间件
中間件是在服務器接受請求之前或之后執行的函數。它們用于修改傳遞給路由處理函數的request,或是由處理函數生成的response對象。
中間件類型
中間件有兩種類型:request和response,都是通過@app.middleware修飾器來聲明的,以修飾器的字符串參數request或response來表示這兩種類型。
請求中間件只接受request對象作為參數。
響應中間件同時接受request和response兩個對象作為參數。
下面是一個最簡單的中間件的例子,它沒有改變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")
修改request或response
中間件可以修改作為參數傳遞的request或response,但不需要返回它們,參見下面的例子:
from sanic import Sanic
from sanic import response
app = Sanic(__name__)
@app.middleware('request')
async def add_key(request):
# Add a key to request object like dict object
request['foo'] = 'bar'
@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.route('/')
async def home(request):
return response.text(request['foo'])
app.run(host="127.0.0.1", port=8888, debug=True)
上面的代碼將按順序應用3個中間件。第一個中間件add_key給request對象增加了一個新的鍵foo,這樣可以工作是因為request對象可以像字典那樣被操作。
第二個中間件custom_banner修改了HTTP響應的頭,把Server設置成Fake-Server。
最后一個中間件prevent_xss添加了響應頭以防止跨站點腳本(XSS)攻擊。
response類型的中間件在路由處理函數(比如,本例中的home()返回response后被調用。
使用curl訪問上面代碼的鏈接:
curl -i http://127.0.0.1:8888
我們可以看到:
HTTP/1.1 200 OK
Connection: keep-alive
Keep-Alive: 5
x-xss-protection: 1; mode=block
Server: Fake-Server
Content-Length: 3
Content-Type: text/plain; charset=utf-8
bar
提前響應
這里的“提前”是指中間件直接返回HTTPResponse對象,這時請求將停止處理并返回response。如果這發生在request類型的中間件,路由處理函數將不會被調用。返回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')
因為中間件halt_request返回了Response對象,其后續的中間件halt_response就不會被執行。
我的公眾號:猿人學 Python 上會分享更多心得體會,敬請關注。
***版權申明:若沒有特殊說明,文章皆是猿人學 yuanrenxue.com 原創,沒有猿人學授權,請勿以任何形式轉載。***
總結
以上是生活随笔為你收集整理的python middleware_Sanic middleware – 中间件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 交管12123APP可有奖举报交通违法?
- 下一篇: 2022全球动力电池装机量排行榜:宁德时