日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python middleware_Sanic middleware – 中间件

發布時間:2023/12/15 python 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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 – 中间件的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。