sanic官方文档解析之websocket(网络套接字)和handle decorators(处理程序装饰器)

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})
原文地址:https://www.cnblogs.com/ljc-0923/p/10391814.html