Does Django have a way to open a HTTP long poll connection?

后端 未结 3 1944
刺人心
刺人心 2020-12-01 12:50

Leave the connection open, until an event occurs.

3条回答
  •  猫巷女王i
    2020-12-01 13:37

    I think the best way to asynchronous communication with Django is have a node server listening in another port and use the api client of Socket.io. In this way, you aren't dependent of the support of the modules for django and is very simple: Node listening the request from client, convert this request in a post request and send to Django for the port which listen Django. Is the best way i think.

    server.js

    var http=require('http');
    var server = http.createServer().listen(3000);
    var io=require('socket.io').listen(server);
    var querystring=require('querystring');
    
    io.on('connection',function(socket){
       console.log('Connected to the client');
       socket.on('new comment',function(data){
          console.log('Web--->Node');
          var values=querystring.stringify(data);
          console.log(values);
          var options={
            hostname:'localhost',
            port:'8000',
            path:'/create-comment',
            method:'POST',
            headers:{
              'Content-Type':'application/x-www-form-urlencoded',
              'Content-Length':values.length
            }
          }
          var request=http.request(options, function(response){
            response.setEncoding('utf8');
            response.on('data',function(data){
              //Here return django
              console.log('Django-->Node');
              io.emit('return comment',data);
            });
          });
    
          request.write(values);
          request.end();
       });
    });
    

    views.py

    def trysock(request):
        print 'In tryshok'
        comments=Comment.objects.all()
        dic = {
                  'name': 'User',
                  'form': CommentForm(),
                  'comments': comments
              }
    
        return render(request,'index.html',dic)
    
    @csrf_exempt
    def create_comment(request):
        print 'Django<---Node'
        Comment.objects.create(
                user = request.POST['user'],
                comment = request.POST['comment']
            )
    
        response = JsonResponse({'user' : request.POST['user'], 'comment' : request.POST['comment']})
        print response.content
        return HttpResponse(response.content)
    

    index.html

    {% csrf_token %} {{form.comment}}
    {% for comment in comments %}

    {{ comment.user }} - {{ comment.comment}}

    {% endfor %}

提交回复
热议问题