【问题标题】:How to subscribe to all instances of a model in django channels rest framework?如何订阅django频道rest框架中模型的所有实例?
【发布时间】:2021-01-03 00:54:18
【问题描述】:

我想将 API 的行为更改为 JSON 触发(从浏览器调用),但由于我对 Python 的了解有限,我什至无法从 Python 客户端调用它。

有人可以帮我解决如何像manual 节目那样做吗?这是我的简单客户:

class GenericAsyncAPIConsumerWith(GenericAsyncAPIConsumer):
    async def websocket_connect(self, message):

        # Super Save
        await super().websocket_connect(message)

        # Initialized operation
        await self.model_activity.subscribe()


class UserConsumer(ObserverModelInstanceMixin, GenericAsyncAPIConsumerWith):
    queryset = Course.objects.order_by("-start_time")
    serializer_class = UserSerializer
    # permission_classes = [IsAuthenticated]


@model_observer(User)
async def model_activity(self, message, observer=None, **kwargs):
    # send activity to your frontend
    await self.send_json(message)    

【问题讨论】:

标签: python django-rest-framework django-channels


【解决方案1】:

当我这样做时,我没有收到任何有关更改的信息。我成功连接到路由,但是当我修改产品时,我没有从服务器收到任何消息到客户端。

这是我的消费者:

class ProductConsumer(AsyncAPIConsumer):
    async def accept(self, **kwargs):
        await super().accept(** kwargs)
        await self.model_change.subscribe()

    @model_observer(Product)
    async def model_change(self, message, **kwargs):
        await self.send_json(message)

【讨论】:

  • 你检查服务器上的任何异常吗?什么是authen方法?
【解决方案2】:

我觉得文档有点不清楚,这是解决方案,也是公关。

class ModelConsumerObserver(AsyncAPIConsumer):
    async def accept(self, **kwargs):
        await super().accept()
        await self.model_change.subscribe()
    
    @model_observer(models.Test)
    async def model_change(self, message, **kwargs):
        await self.send_json(message)

从那时起,websocket 会将模型更改推送到客户端

【讨论】:

    猜你喜欢
    • 2016-10-12
    • 2014-11-29
    • 2019-09-07
    • 2013-11-18
    • 2018-12-10
    • 1970-01-01
    • 2018-07-30
    • 1970-01-01
    • 2021-02-15
    相关资源
    最近更新 更多