使用Django Channels和WebSockets工作

3

我是一名有用的助手,可以为您进行文本翻译。以下是需要翻译的内容:

我有一个表单可以在127.0.0.1:8000/dashboard/输入线坐标,并有一个“确定”按钮提交坐标。通过调用视图LineDisplay()将坐标发布到127.0.0.1:8000/api/line/。在这里,我想将线坐标推送回127.0.01:8000/dashboard/

到目前为止,我已经完成了以下工作:

urls.py:

from django.conf.urls import url,include
from django.contrib import admin
from . import views

urlpatterns = [
    url(r'^api/line/$',views.LineDisplay.as_view()),
]

view.py:

class LineDisplay(APIView):
"""
Display the most recent line
"""

    def get(self, request, format=None):
        lines = Line.objects.all()
        serializer = LineSerializer(lines, many=True)
        return Response(serializer.data)

    def post(self, request, format=None):
        lines = Line.objects.all()
        for line in lines:
            line.delete();
        serializer = LineSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
        info = ""
        info += "Line Coordinates are: "
        lines = Line.objects.all()
        for line in lines:
            info += "x1:" + str(line.x1)
            info += " y1:" + str(line.y1)
            info += " x2:" + str(line.x2)
            info += " y2:" + str(line.y2)
        print info
        Channel('repeat-me').send({'info': info, 'status': True})
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

consumers.py

import json

# In consumers.py
from channels import Group

# Connected to websocket.connect
def ws_add(message):
    Group("chat").add(message.reply_channel)

# Connected to websocket.receive
def ws_message(message):
     print "Receive Message now"
     Group("chat").send({
        "text": json.dumps({'status': False})
    })
# Connected to websocket.disconnect
def ws_disconnect(message):
    Group("chat").discard(message.reply_channel)


def repeat_me(message):
    Group("chat").send({
    "text": json.dumps({'status': message.content['status'], 'info':      
     message.content['info']})
     })

同样地,我已经将以下代码添加到:routing.py文件中。
from channels.routing import route
from .consumers import ws_add, ws_message, ws_disconnect, repeat_me

channel_routing = [
    route("websocket.connect", ws_add),
    route("websocket.receive", ws_message),
    route("websocket.disconnect", ws_disconnect),
    route("repeat-me", repeat_me),
]

以下内容已添加到settings.py文件中:
CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "asgiref.inmemory.ChannelLayer",
        "ROUTING": "TrainingInduct.routing.channel_routing",
    },
}

目前,我不知道如何处理“聊天”组。我甚至不需要一个组。为了在新的线路被发布时立即在127.0.0.1:8000/dashboard/上显示线路坐标,还有哪些剩余的工作需要完成?

注意:线路坐标已经正确地发布到/api/line/。我认为我可能需要编写服务器代码来从频道获取数据并将其推回,是吗?谢谢。

1个回答

5
你需要一个组来收集所有应该接收你信息的频道。每个连接的设备都会有一个频道。
设备的频道标识符在 `message.reply_channel` 中。一个 Group 只是一种收集所有 `message.reply_channel` 的方式。
所以,假设任何打开你的 `/dashboard/` 页面的用户都将收到发布的任何新 "info" 项目。首先,你需要记住新客户端的 Channel。这就是你的 `ws_add` 的作用。
def ws_add(message):
    Group("all-my-clients").add(message.reply_channel)

现在刚连接的客户端是“all-my-clients”组的一部分,通过“all-my-clients”发送的任何消息都会自动发送到该客户端。当然,您需要在使用完后清理资源,这就是“ws_disconnect”的作用。一旦客户端执行WebSocket.close()或关闭其浏览器等操作,就要将其移除。
def ws_disconnect(message):
    Group("all-my-clients").discard(message.reply_channel)

最后,还有你的ws_message()函数。它接收任何传入的消息。

def ws_message(message):
    # Nothing to do here, because you only push, never receive.
    pass

这就是全部内容。现在你可以在Django的任何地方向之前定义的群组发送消息了。只需确保以正确的格式发送响应即可。 Group().send()接受一个带有键为textdict,其值为字符串(见下文)。原因是你也可以发送其他数据类型,如Blob。但对于此目的,“text”最好。

def post(self, request, format=None):
    lines = Line.objects.all()
    ...
    print info
    response_data = {'info': info, 'status': True}
    Group("all-my-clients").send({
        'text': json.dumps(response_data)
    })
    return Response(serializer.data, status=status.HTTP_201_CREATED)

这就是全部。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接