使用django通道的websockets的restful api。
djangochannelsrestframework的Python项目详细描述
django channels rest框架为构建channels-v2 websocket消费者提供了一个类似drf的接口。
这个项目可以与HyperMediaChannels和ChannelsMultiplexer一起使用,在websockets上创建一个超媒体风格的api。然而,django channels rest框架也是一个独立的框架,其目标是提供drf用户熟悉的api。
感谢
dcrf基于Channels Api的叉,当然灵感来自Django Rest Framework。
安装
pip install djangochannelsrestframework
如何使用
观察模型实例
接受实例订阅的使用者。
classTestConsumer(ObserverModelInstanceMixin,GenericAsyncAPIConsumer):queryset=get_user_model().objects.all()serializer_class=UserSerializer
这将向该实例公开retrieve和subscribe_instance操作。
订阅发送:
{"action":"subscribe_instance","pk":42,# the id of the instance you are subscribing to"request_id":4# this id will be used for all resultent updates.}
操作将从服务器发送出去:
{"action":"update","errors":[],"response_status":200,"request_id":4,"data":{'email':'42@example.com','id':42,'username':'thenewname'},}
添加自定义操作
classUserConsumer(GenericAsyncAPIConsumer):queryset=get_user_model().objects.all()serializer_class=UserSerializer@action()asyncdefsend_email(self,pk=None,to=None,**kwargs):user=awaitdatabase_sync_to_async(self.get_object)(pk=pk)# ... do some stuff# remember to wrap all db actions in `database_sync_to_async`return{},200# return the contenct and the response code.@action()# if the method is not async it is already wrapped in `database_sync_to_async`defpublish(self,pk=None,**kwargs):user=self.get_object(pk=pk)# ...return{'pk':pk},200
您也可以使用以下任一选项:
- CreateModelMixin
- ListModelMixin
- RetrieveModelMixin
- UpdateModelMixin
- PatchModelMixin
- DeleteModelMixin
就像你在drf里一样。
fromdjangochannelsrestframework.genericsimportGenericAsyncAPIConsumerfromdjangochannelsrestframework.mixinsimport(RetrieveModelMixin,UpdateModelMixin)classUserConsumer(RetrieveModelMixin,UpdateModelMixin,GenericAsyncAPIConsumer):queryset=get_user_model().objects.all()serializer_class=UserSerializer
不受车型约束的消费者
您还可以创建与任何模型都不相关的消费者。
fromdjangochannelsrestframework.decoratorsimportactionfromdjangochannelsrestframework.consumersimportAsyncAPIConsumerclassMyConsumer(AsyncAPIConsumer):@action()asyncdefan_async_action(self,some=None,**kwargs):# do something asyncreturn{'response with':'some message'},200@action()defa_sync_action(self,pk=None,**kwargs):# do something syncreturn{'response with':'some message'},200
在WebSocket连接上使用普通视图
fromdjangochannelsrestframework.consumersimportview_as_consumerapplication=ProtocolTypeRouter({"websocket":AuthMiddlewareStack(URLRouter([url(r"^front(end)/$",view_as_consumer(YourDjangoView)),])),})