wsrpc是aiohttp的websocket上的rpc
wsrpc-aiohttp的Python项目详细描述
易于使用的aiohttp的最小websocket远程过程调用库 服务器。
请参见online demo和documentation中的示例。
功能
- 从客户端调用服务器函数;
- 从服务器调用客户端函数(例如通知客户端 事件);
- 异步连接协议:服务器或客户端都可以调用 函数并在每个响应准备就绪后立即获取响应 命令。
- 完全异步服务器端功能;
- 将任何异常从客户端传输到服务器端,反之亦然;
- 无需依赖项即可使用前端库;
- 用于编写完全同步后端代码的基于线程的WebSocket处理程序 (用于同步数据库驱动程序等)
- 受保护的服务器端方法(客户端无法调用方法,正在启动 直接用下划线);
安装
通过PIP安装:
pip install wsrpc-aiohttp
您可能需要安装可选的ujson库来加速消息序列化/反序列化:
pip install ujson
python模块提供了现成的客户端js库。但是对于纯javascript应用程序,您可以安装standalone js client library 使用NPM:
npm install @wsrpc/client
用法
后端代码:
importloggingfromtimeimporttimeimportaiohttp.webfromwsrpc_aiohttpimportWebSocketAsync,STATIC_DIR,WebSocketRoutelog=logging.getLogger(__name__)# This class can be called by client.# Connection object will have this class instance after calling route-alias.classTestRoute(WebSocketRoute):# This method will be executed when client calls route-alias# for the first time.definit(self,**kwargs):# Python __init__ must be return "self".# This method might return anything.returnkwargs# This method named by camelCase because the client can call it.asyncdefgetEpoch(self):# You can execute functions on the client sideawaitself.do_notify()returntime()# This method calls function on the client sideasyncdefdo_notify(self):awesome='Somebody executed test1.getEpoch method!'awaitself.socket.call('notify',result=awesome)app=aiohttp.web.Application()app.router.add_route("*","/ws/",WebSocketAsync)# Websocket routeapp.router.add_static('/js',STATIC_DIR)# WSRPC js libraryapp.router.add_static('/',".")# Your static files# Stateful request# This is the route alias TestRoute as "test1"WebSocketAsync.add_route('test1',TestRoute)# Stateless requestWebSocketAsync.add_route('test2',lambda*a,**kw:True)if__name__=='__main__':logging.basicConfig(level=logging.DEBUG)aiohttp.web.run_app(app,port=8000)
前端代码:
<scripttype="text/javascript"src="/js/wsrpc.min.js"></script><script>varurl=(window.location.protocol==="https):"?"wss://":"ws://")+window.location.host+'/ws/';RPC=newWSRPC(url,8000);// Configure client API, that can be called from server RPC.addRoute('notify',function(data){console.log('Server called client route "notify":',data);returndata.result;});RPC.connect();// Call stateful route // After you call that route, server would execute 'notify' route on the // client, that is registered above. RPC.call('test1.getEpoch').then(function(data){console.log('Result for calling server route "test1.getEpoch": ',data);},function(error){alert(error);});// Call stateless method RPC.call('test2').then(function(data){console.log('Result for calling server route "test2"',data);});</script>
版本控制
这个软件遵循Semantic Versioning