Django 频道中发送到消费者之外的消息未被接收

时间:2021-03-02 02:22:19

标签: django-channels

我正在尝试将消息发送到特定的 websocket 实例,但无论是 channel_layer.send,还是使用 channel_layer.group_send 和每个实例的唯一组似乎都没有工作,没有出现错误,只是没有被接收实例。

发送消息的函数是:

def listRequest(auth_user, city):
    request_country = city["country_name"]
    request_city = city["city"]
    request_location = request_city +", "+request_country
    concatenate_service_email = auth_user.service + "-" + auth_user.email
    this_request = LoginRequest(service_and_email=concatenate_service_email, location=request_location)
    this_request.generate_challenge()
    this_request.set_expiry(timezone.now() + timezone.timedelta(minutes=5))
    this_request.save()
    channel_layer = get_channel_layer()
    print(auth_user.current_socket)
    async_to_sync(channel_layer.group_send)(
        auth_user.current_socket,{
            "type": "new.request",
            "service_and_email" : concatenate_service_email
        },
    )

我当前工作的consumers.py(接收和扫描请求没有任何可能与问题相关的内容):

from asgiref.sync import async_to_sync
from channels.generic.websocket import WebsocketConsumer
from .helpers import verify_identity, unique_group
from django.utils import timezone
from .models import Authentication, LoginRequest
import json
import time
class AuthConsumer(WebsocketConsumer):
    account_list =[]

    def connect(self):
        print("Connect attempted")
        print(self.channel_name)
        print(unique_group(self.channel_name))
        async_to_sync(self.channel_layer.group_add)(unique_group(self.channel_name), self.channel_name)
        self.accept()

    def disconnect(self, close_code):
        print("Disconnect attempted")
        async_to_sync(self.channel_layer.group_discard)(unique_group(self.channel_name), self.channel_name)
        for i in self.account_list:
            serviceEmailSplit = i.split("-")
            try:
                auth_user = Authentication.objects.get(service=serviceEmailSplit[0],email=serviceEmailSplit[1])
                auth_user.set_socket("NONE")
                auth_user.save()
            except:
                print("Error user %s does not exist" %i)
        pass

    def receive(self, text_data):
        print("Receiving data")
        if text_data[0:7] == "APPROVE":
            data_as_list = text_data.split(",")
            serviceEmailSplit = data_as_list[1].split("-")
            auth_user = Authentication.objects.get(service=serviceEmailSplit[0],email=serviceEmailSplit[1])
            this_request = LoginRequest.objects.get(service_and_email=data_as_list[1],approved=False, expiry__gt=timezone.now())
            if verify_identity(auth_user.public_key, data_as_list[2], this_request.challenge):
                this_request.set_approved()
                self.send("Request Approved!")
            else:
                self.send("ERROR: User verification failed")
        else:
            self.account_list = text_data.split(",")
            self.account_list.pop(-1)
            print(self.account_list)
            for i in self.account_list:
                serviceEmailSplit = i.split("-")
                try:
                    auth_user = Authentication.objects.get(service=serviceEmailSplit[0],email=serviceEmailSplit[1])
                    auth_user.set_socket(unique_group(self.channel_name))
                    auth_user.save()
                except:
                    self.send("Error user %s does not exist" %i)
            self.scanRequest()
    def scanRequest(self):
        requestSet = LoginRequest.objects.filter(service_and_email__in = self.account_list, approved = False, request_expiry__gt = timezone.now())
        if requestSet.count() > 0:
            for request in requestSet:
                self.send(request.service_and_email+","+request.location+","+str(request.challenge))
        else:
            self.send("NOREQUESTS")

    def new_request(self,event):
        print("NEW REQUEST!")
        this_request = LoginRequest.objects.filter(service_and_email = event["service_and_email"]).latest('request_expiry')
        self.send(this_request.service_and_email+","+this_request.location+","+str(this_request.challenge))

还有我的routing.py:

from django.urls import re_path
from . import consumers
from django.conf.urls import url

websocket_urlpatterns = [
    url(r"^ws/$", consumers.AuthConsumer.as_asgi()),
]

“新请求!”从未打印,尝试通过直接发送消息来调用它,也没有像我上面写的那样使用组。

我的 redis 服务器似乎正在测试,就像频道教程的文档所建议的那样: https://channels.readthedocs.io/en/stable/tutorial/part_2.html

在尝试修复它后,我非常难受,我已经查看了关于 stackoverflow 的其他帖子,其中包含相同/类似的问题,并且我已经在遵循他们在我的代码中提供的任何解决方案。

0 个答案:

没有答案