Django、Vue 和 WebSocket - 让客户端工作

Django, Vue and WebSocket - getting client side to work

前段时间在 SO 上也有类似的问题,虽然我尝试了答案但没有成功。

我正在使用 Django 后端和 Vue 前端以及 Vue cli 实现 SPA。 Django 正在使用通道通过 WebSocket 将 JSON 发送到前端,前端接收到此数据并应该更新 table.

Django 部分正在运行。已确认与 WebSocket 的连接并在 Vue 中接收到数据,但我有两个问题无法找到解决方法:

  1. 数据虽然在变量中,但未显示在 table 和
  2. 前端只接收一次数据 - 我不知道如何将侦听器应用于 WebSocket,或者在我的 Vue 应用程序的哪个部分,以便新的有效负载(我希望我说的是正确的)收到并相应更新。

下面我提供了 Django consumers.py 文件、Signals.vue 视图文件和 console.log 输出显示变量确实包含 JSON 对象,尽管table留白。

有没有人知道我哪里出错了以及如何解决问题 1 和 2? 谢谢

Django consumers.py

import json
from channels.generic.websocket import WebsocketConsumer


class WSConsumer(WebsocketConsumer):
    def connect(self):
        self.accept()

        self.send(json.dumps({
            'id': 1,
            'date': "date",
            'marketOpen': "marketOpen",
            'symbol': "symbol",
            'trade': "trade",
            'bias': "bias",
            'status': "status"
            }))

Signals.vue

<template>
    <div class="container">
        <div class="columns is-multiline">
            <div class="column is-12">
                <h1 class="title"> Signals</h1>
            </div>

            <div class="column is-12">
                <table class="table is-fullwidth">
                    <thead>
                        <tr>
                            <th>Date</th>
                            <th>Market Open</th>
                            <th>Symbol</th>
                            <th>Trade</th>
                            <th>Bias</th>
                            <th>Status</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for= "signal in signals" v-bind:key="signal.id">
                            <td>{{ signal.date }} </td>
                            <td>{{ signal.marketOpen }} </td>
                            <td>{{ signal.symbol }} </td>
                            <td>{{ signal.trade }} </td>
                            <td>{{ signal.bias }} </td>
                            <td>{{ signal.status }} </td>
                        </tr>
                    </tbody>    
                </table>
            </div>
            
        </div>
    </div>
</template>

<script>
export default {
    name: 'Signals',
    data() {
        return {
            signals: [],
            connection: null
        }
    },
    created() {
        this.getSignals()
    },
    methods: {
        getSignals() {
            console.log("Starting connection to websocket")
            this.connection = new WebSocket('ws://localhost:8000/ws/signals/')
            this.connection.onmessage = (event) => {
                this.signals = event.data
                console.log("Successfully retrieved message from websocket")
                console.log(this.signals)
            }
        }
    }
}
</script>

控制台

[HMR] Waiting for update signal from WDS... log.js?1afd

Starting connection to websocket Signals.vue?1d80

Unchecked runtime.lastError: The message port closed before a response was received. signals:1

Successfully retrieved message from websocket Signals.vue?1d80

{"id": 1, "date": "date", "marketOpen": "marketOpen", "symbol": "symbol", "trade": "trade", "bias": "bias", "status": "status"} Signals.vue?1d80

要异步发送消息,您应该使用 async, 并编写一个异步函数来根据要求发送数据,调用 view.py 中的发送函数或 celery worker,如果你想定期发送 celery beat 是要走的路,否则使用 celery worker for on-demand数据.

第一次在堆里回答问题,如有理解错误或回答有误请见谅。我不确定你的第一个问题是什么。 (我刚刚开始学习 Vue js,但我在 Django 上工作了多年,所以我想我可以回答这个问题,感谢所有在 whosebug.com 中帮助我回复的人)

下面是我实现的socket连接的简单例子:

class NotificationConsumer(AsyncWebsocketConsumer):
async def connect(self):
    # this only exicutes only once when a user gets connected to the socket
    self.room_name = self.scope['url_route']['kwargs']['room_name']
    self.room_group_name = 'notification_%s' % self.room_name

    # Join room group
    await self.channel_layer.group_add(
        self.room_group_name,
        self.channel_name
    )

    await self.accept()

async def disconnect(self, close_code):
    # Leave room group
    await self.channel_layer.group_discard(
        self.room_group_name,
        self.channel_name
    )

Receive message from WebSocket
async def receive(self, text_data):
    text_data_json = json.loads(text_data)
    message = text_data_json['message']
    print(message)
    print("message")

    # Send message to room group
    await self.channel_layer.group_send(
        self.room_group_name,
        {
            'type': 'snmpop_message',
            'message': message
        }
    )


async def send_notification(self, event):
    message = json.loads(event['message'])
    print(message)
    # Send message to WebSocket
    await self.send(text_data=json.dumps(message))

#这就是我将按要求发送数据的方式:从任何其他地方:

channel_layer = get_channel_layer()
async_to_sync(channel_layer.group_send)(
    "notification_broadcast",
    {
        'type': 'send_Notification',
        'message': json.dumps(outputdict)
    }
 )

如果你们有任何疑问,可以联系我:amithkhul@gmail.com 谢谢 阿米斯 K