2

私は127.0.0.1:8000/dashboard/にライン座標を入力するフォームがあり、座標を送信するには「OK」ボタンを押します。座標は、LineDisplay()を呼び出して、127.0.0.1:8000/api/line/に転記されます。ここでは、ライン座標を127.0.01:8000 /ダッシュボード/に戻したいとします。djangoチャンネルとウェブソケットの使用

私がこれまでに次のように行われている:

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/に正しくPOSTEDされています。チャンネルのデータを取得して戻すためにサーバーコードを記述する必要があると思いますか?ありがとう。

答えて

4

お客様の情報を受け取るすべてのチャンネルを収集するには、グループが必要です。接続された各デバイスは1つのチャネルを取得します。

デバイスのチャネルIDはmessage.reply_channelです。グループは、message.reply_channelのすべてを収集する単なる方法です。

あなたの/dashboard/ページを開くユーザーには、新しい「情報」アイテムが投稿されます。まず、新しいクライアントのチャンネルを覚えておく必要があります。それはあなたの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()は、文字列値を持つtextキー(下記参照)を使用してdictとなります。その理由は、ブロブのような他のデータ型を送ることもできるからです。しかし、この目的には "テキスト"が最適です。

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) 

すべてである必要があります。

関連する問題