Python 使用django频道和WebSocket
我有一个表单可以在127.0.0.1:8000/仪表板/处输入线坐标,还有一个“Ok”按钮可以提交坐标。通过调用视图Python 使用django频道和WebSocket,python,django,websocket,django-rest-framework,django-channels,Python,Django,Websocket,Django Rest Framework,Django Channels,我有一个表单可以在127.0.0.1:8000/仪表板/处输入线坐标,还有一个“Ok”按钮可以提交坐标。通过调用视图LineDisplay(),坐标在127.0.0.1:8000/api/line/处发布。这里我想把线坐标推回到127.0.01:8000/dashboard/ 到目前为止,我已经做了以下工作: URL.py: from django.conf.urls import url,include from django.contrib import admin from . impor
LineDisplay()
,坐标在127.0.0.1:8000/api/line/处发布。这里我想把线坐标推回到127.0.01:8000/dashboard/
到目前为止,我已经做了以下工作:
URL.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)
消费者.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/仪表板/位置,还需要做哪些工作
注意:测线坐标被正确地发布到/api/Line/我想我可能需要编写一个服务器代码,以便从通道获取数据并将其推回,对吗?谢谢。您需要小组收集所有应该接收您信息的频道。每个连接的设备都有一个通道 设备的通道标识符在
消息中。回复\u通道
。分组只是收集所有消息的一种方式。回复频道
因此,假设任何打开您的/dashboard/
页面的用户都将收到发布的任何新“信息”项。首先,您需要记住新客户的渠道。这就是你的ws\u add
的目的
def ws_add(message):
Group("all-my-clients").add(message.reply_channel)
现在,刚刚连接的客户端是所有我的客户端
组的一部分,您通过所有我的客户端
发送的任何消息也将自动发送到该客户端
当然,您希望自己清理干净,所以这就是ws\u disconnect
的用途。执行WebSocket.close()或关闭浏览器等操作后删除客户端
def ws_disconnect(message):
Group("all-my-clients").discard(message.reply_channel)
最后,还有您的ws\u message()
。它接收任何传入的消息
def ws_message(message):
# Nothing to do here, because you only push, never receive.
pass
就这些。现在,您可以从Django中的任何位置向上面定义的组发送消息。只需确保您以正确的格式发送响应Group().send()
接受一个带有字符串值的键text
的dict
(见下文)。原因是您还可以发送其他数据类型,如blob。但“文本”最适合于此目的
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)
就这些了