一个基于django通道的restfulapi流系统,具有模型绑定自动化功能
channels-binding的Python项目详细描述
通道绑定API
通道绑定通过channels公开JSON API流系统, 它被设计成通过websocket、http或两者结合的方式作为一个功能齐全的RestAPI。 在很少的代码行中,使用非常简单和无冗余的交换结构, 每一个django模型都可以很容易地绑定起来,并附带一些本机的基本操作,如“检索”、“搜索”、“更新”、“创建”、“删除”和“订阅”。 我们可以将django restframework与REST系统进行比较。 它还为react包提供了可随时使用的预先配置的工具和组件,以方便应用程序ui。在
通道绑定是somes包的汇编:
能力
- 支持“检索”、“表单”、“搜索”、“列表”、“更新”、“创建”、“保存”、“删除”、“订阅”事件
- 支持django信号,用React工具刷新任何连接的实例
- 支持原生django Queryset into React(提供材料用户界面表)
- 支持原生django Form into React(提供Material UI字段)
- 同一个订阅方/流支持不同的事件/流的示例
- 订阅感兴趣组的自动频道“检索”、“列表”、“删除”
- 通过装饰器自定义绑定事件
- 与Django restframework序列化程序兼容(即将就绪)
- 异步或同步使用者(尚未)
- HTTP Rest或WS-API(尚未)
交易所结构概述
SELFSEND=>{event:"auth.User.search",data:{page:2}}SELFRECEIVE=>{event:"auth.User.search",data:{page:2,limit:25,count:102,rows:[{id:5763,username:"Admin",email:"admin@admin.com"},...]}}SELFSEND=>{event:"auth.User.retrieve",data:{id:5763}}SELFRECEIVE=>{event:"auth.User.retrieve",data:{id:5763,username:"Admin",email:"admin@admin.com",...andMoreDetails}}SELFSEND=>{event:"auth.User.update",data:{id:5763,username:"Changed Username"}}SELFRECEIVE=>{event:"auth.User.update",data:{success:true}}GROUPRECEIVE=>{event:"auth.User.retrieve",data:{id:5763,username:"Changed Username",email:"admin@admin.com",...andMoreDetails}}
入门
- 假设您已经安装了django>;=1.8和channels>;=2.0.0
- 将channels-binding添加到要求.txt在
- 将channels_binding添加到INSTALLED_APPS
INSTALLED_APPS=('channels','channels_binding',)
- {$TTN配置^4}
CHANNEL_LAYERS={'default':{# ...someChannelsConfig},}CHANNELS_BINDING={"AUTHENTIFICATION_CLASSES":('authentification.AuthenticationStrategyClass',),"DEFAULT_PAGE_SIZE":25,"ANONYMOUS_CONNECTION_ALLOWED":False,# Reject connection of non connected users}
- 在您的asgi应用程序路由中添加一个新的AsyncConsumer(阅读channels文档)
# asgi.pyfromdjango.urlsimportpathfromchannels.sessionsimportSessionMiddlewareStackfromchannels.routingimportProtocolTypeRouter,URLRouterfromchannels_binding.consumersimportAsyncConsumerapplication=ProtocolTypeRouter({'websocket':SessionMiddlewareStack(URLRouter([path('',AsyncConsumer,name="root"),]))})
- 在应用程序或根bindings文件夹中添加bindinds
# apps/your_app/bindings.pyfromchannels_binding.consumersimportAsyncBindingfrom.modelsimportYourModel''' All bindings in apps/*/bindings.py or app/bindings/*.py are auto discovered, like models.py '''classYourModelBinding(AsyncBinding):model=YourModel# stream = by default '{app_name.model_name}' if model is set# permission_class = by default None (may change in future)# serializer_class = by default None (soon compatible with restframwork serializer)# queryset = by default YourModel.objects.all()# page_size = by default 25 rows for the 'search' and 'list' events# post_save_retrieve = by default True, if is True, an instance post_save send the 'retrieve' event to all the stream subscribers
- 让我们开始在一个前端javascript第三方上使用一个简单的检索操作进行通信
// Soon React example...
varws=newWebSocket("ws://"+window.location.host+"/")ws.onmessage=function(e){console.log(e.data)/* Receive: { event: "your_app.YourModel.retrieve", data: { id: 5763, ...someData } } */}ws.send(JSON.stringify({event:"your_app.YourModel.retrieve",data:{id:5763}}))
反应前沿集成
- 假设您已经安装了react
- npm安装@channels binding/core
- 与物料界面集成
- npm安装@channels binding/mui
绑定自定义事件
- 使用添加完全自定义绑定
# apps/your_app/bindings.pyfromchannels_binding.consumersimportAsyncBinding,bindclassYourCustomBinding(AsyncBinding):stream='custom_stream'@bind('custom_event')asyncdefhandle_custom_event(self,data):sender=data['sender']# Direct reflect the reponse to the current socket pipeawaitself.reflect('custom_event',{'msg':f'This a reflected response for {sender}'})# Send an event to this stream subscribersawaitself.dispatch('custom_group_event',{'msg':f'This a dispatched response to the custom_stream subscriber from {sender}'})# Send an event to this stream subscribersawaitself.broadcast('custom_all_event',{'msg':f'This a dispatched response to the all layers from {sender}'})
- 让我们在前面的javascript第三方上试试这个
varws=newWebSocket("ws://"+window.location.host+"/")ws.onmessage=function(e){console.log(e.data)/* Receive (reflected): { event: "custom_stream.custom_event", data: { msg: 'This a reflected response for me!!!' } } Receive (from group to all "custom_stream" subscribers): { event: "custom_stream.custom_group_event", data: { msg: 'This a dispatched response to the custom_stream subscriber from me!!!' } } Receive (broadcasted to all): { event: "custom_stream.custom_all_event", data: { msg: 'This a dispatched response to the all layers from me!!!' } } */}ws.send(JSON.stringify({event:"custom_stream.custom_event",data:{sender:'me!!!'}}))
- 项目
标签: