Django 长轮询请求超时

Django long polling request timed-out

  1. Django 3.2
  2. DRF
  3. 运行 使用 ./mange 运行server
  4. 部署规划时使用'nginx, uwsgi'

这是我的后端代码

class ChatHandler(APIView):
queryset = Chat.objects.all()
serialzier_class = MessageSerializer



def get_queryset(self):
    return self.queryset.filter(name=self.kwargs['room']).get()

def get(self, request, room):
    optionail_last_message_time  = request.data.get('at')
    new_messages = self.get_queryset().messages.filter(is_viewed=False)
    while not new_messages.exists():
        print(timezone.localtime().time(), 'no new messages')
        sleep(3)


    print(dir(self))
    print(dir(self.request))
    print('oh here it is')
    last_time = new_messages.last().created_at.timestamp()
    serializered_new_messages  = self.serialzier_class(instance=new_messages, many=True).data
    new_messages.update(is_viewed=True)

    return Response(
        {
            'messages': serializered_new_messages,
            'last_time': last_time,
            'initial': False
        }, status=200
    )

这是前端代码

 function textRequest(last_time) {
    $.ajax({
        method:'GET',
        url:long_url,
        data: {'at': last_time},                
        timeout:2000,   
        success : (data, status, xqhr) => {
            console.log(last_time)
            let messages = data['messages']
            console.log(messages)
            if (messages) {
                for (let message of messages) {
                    console.log(message)
                    inject_message(message)
                }
            }

            setTimeout(()=>{
                textRequest(data['last_time'])
            }, 5000)    
        },
        error: (error, status_text, xqhr)=> {
            if ((error.readyState == 0) && (status_text =='timeout')) {
                console.log(status_text)
                textRequest()
                console.log('sent')
            }
        },
    })

}

window.addEventListener('load', ()=>{
    textRequest()
})

问题:

  1. 当我刷新页面时,它会向
    发送一个新请求 后端,并将继续发送请求, 后端服务器收到数百个请求

问题:如何限制接收请求的数量?

  1. 当服务器找到数据,并将其处理回前端时, 响应没有到达“前端”那里,因为它是请求 已经死了'达到超时限制'

问题:我应该怎么做才能避免这种情况? 问题:有没有办法从后端知道请求是否已经超时?

请求:能否请您提供我在 Django 中实现长轮询,我在这个问题上卡了几天?

提前致谢

我能够通过以下后端代码使其工作:

class ChatLongPolling(MainConfig):
serializer_class = MessageSerializer 

def get(self, request, name):
    messages = self.get_queryset().messages
    messages_filter = messages.filter(is_sent=False)
    while not messages_filter.exists():
        print('searching..')
        sleep(1)
        return JsonResponse({'empty':'empty'})
    else:    
        messages = self.serializer_class(instance=messages_filter, many=True).data
        messages_filter.update(is_sent=True)
        print(messages)
        return JsonResponse({'messages': messages})

这里是前端

function make_json_request(url){
    let request = new XMLHttpRequest()
    request.open('get', url)
    request.responseType = 'json'
    request.addEventListener('load', function() {
        let response = request.response
        if (response['messages']){
            let messages = response['messages']
            console.log(messages)
            for (let message of messages) {
                append(message)
            }
        }
    });

    request.addEventListener('abort', function(){
        console.log('abort')
    });

    request.addEventListener('error', function(){
        console.log('error')
        setTimeout(()=>{make_json_request(url)}, 1000);
    });

    request.send()        
}

function get_all_messages(url){
    make_json_request(url)
}

function longpolling(url) {
    make_json_request(url)
    setTimeout(()=>{longpolling(url)}, 1000);
}

send_message()
get_all_messages(store_url)
longpolling(long_url)