sanic官方文檔解析之websocket(網絡套接字)和handle decorators(處理程序裝飾器)
阿新 • • 發佈:2019-02-17
test decorator 方法 實例化 con tco nic max cor
1,websocket(網絡套接字)
在websocket上Sanic提供了一種簡單使用的抽象化,來設置websocket(網絡套接字)
from sanic import Sanic
from sanic.response import json
from sanic.websocket import WebSocketCommonProtocol
# 實例化一個Sanic對象
app = Sanic()
@app.websocket("/feed")
async def feed(request, ws):
while 1:
data = "hello!"
print("Sending:" + data)
# 阻塞發送數據
await ws.send(data)
# 阻塞接收數據
data = await ws.recv()
print("Received:" + data)
if __name__ == ‘__main__‘:
app.run(host="0.0.0.0", port=8000, protocol=WebSocketCommonProtocol) # 指定協議是WebsocketCommonProtocol
app.add_websocket_route方法能夠被替換成路由的裝飾器
from sanic import Sanic
app = Sanic()
async def feed(request, ws):
pass
app.add_websocket_route(feed, "/feed")
調用WebSocket路由的處理程序時,請求作為第一個參數,WebSocket協議對象作為第二個參數。協議對象具有分別發送和接收數據的發送和接收方法
你能夠通過app.config來設置自己的Websocket配置.
app.config.WEBSOCKET_MAX_SIZE = 2 ** 20
app.config.WEBSOCKET_MAX_QUEUE = 32
app.config.WEBSOCKET_READ_LIMIT = 2 **16
app.config.WEBSOCKET_WRITE_LIMIT = 2 ** 16
2,處理程序的裝飾器
自從Sanic處理程序時簡單的Python函數(功能),你可以使用裝飾器去裝飾函數在單一的管理在flask中,一種典型的使用,一個典型的用例就是,當你希望執行處理代碼之前,運行一些代碼時候
- 2.1授權裝飾器
假設您希望檢查用戶是否有權訪問特定端點。您可以創建一個包裝處理程序函數的裝飾器,檢查客戶機是否有權訪問資源,並發送適當的響應。
from functools import wraps
from sanic.response import json
from sanic import Sanic
# 實例化sanic對象
app = Sanic()
def authorized():
def decorator(f):
@wraps(f)
async def decorated_function(request, *args, **kwargs):
# 檢查運行方法中的request請求
# 客戶授權狀態
is_authorized = check_request_for_authorization_status(request) # 執行查看請求校驗狀態的函數
# is_authorized條件成立
if is_authorized:
# 說明這個用戶已經已經被授權了
# 運行這個處理程序的方法並且返回響應
response = await f(request, *args, **kwargs)
return response
else:
# 否則這個用戶沒有被授權
# 返回json格式的數據
return json({"status": "not_authorized"}, 403)
return decorated_function
return decorator
@app.route("/") # 訪問路由
@authorized() # 授權的驗證
async def test(request): # 被裝飾的函數
return json({"status": authorized})
sanic官方文檔解析之websocket(網絡套接字)和handle decorators(處理程序裝飾器)