我有一个表格可以在127.0.0.1:8000/dashboard/处输入线坐标,并有一个“确定”按钮来提交坐标。通过调用 view将坐标发布在127.0.0.1:8000/api/line/LineDisplay()
。在这里,我想将 Line 坐标推回127.0.01:8000/dashboard/。
到目前为止,我已经完成了以下工作:
网址.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()),
]
视图.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/dashboard/上,还需要做些什么?
注意: Line 坐标已正确发布到/api/line/我想我可能必须编写一个服务器代码才能从通道中获取数据并将其推回,对吗?谢谢。