Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django and Long Polling

I need to implement long polling in my application to retrieve the events. But I have no idea how to do it. I know the concept of long polling, i.e to leave the connection open, until an event occurs. But how do I do implement this in my project. If you could give me a simple long polling example of client side and the views i guess, I would really appreciate. Thank you!

like image 817
Robin Avatar asked Mar 22 '14 19:03

Robin


People also ask

What is long polling in Python?

HTTP Long Polling is a technique used to push information to a client as soon as possible on the server. As a result, the server does not have to wait for the client to send a request. In Long Polling, the server does not close the connection once it receives a request from the client.

What is polling Long polling?

Polling is a technique that allows the servers to push information to a client. On another side, long polling is a version of traditional polling that allows the server to send data to a client whenever available.

What is long polling in Websocket?

Long polling takes HTTP request/response polling and makes it more efficient, since repeated requests to a server wastes resources. For example, establishing a new connection, parsing the HTTP headers, a query for new data, response generation and delivery, and finally connection closure and clean up.

What does long poll mean?

long polling (uncountable) (computing) A technology where the client requests information from the server without expecting an immediate response.


1 Answers

Disclaimer: this answer is long outdated. As of 2020, there is a ton of solutions for this problem, with django channels being only one of the options.

<< Disclaimer

very simple example:

import time

def long_polling_view(request):
    for i in range(30): #e.g. reopen connection every 30 seconds
        if something_happened():
            ...
            return http.HttpResponse(
                arbitrary_JSON_content,
                mimetype='application/javascript'
            )
        time.sleep(1)
    return http.HttpResponse({}, mimetype='application/javascript')

from the client side, you have to handle timeout and reopen connection.

However, I should say it's generally bad approach, by a number of reasons:

  • it's computationally expensive both for client and server
  • it's sensible to environment, e.g. timeouts
  • it's still subject to 1 second delay (time.sleep() in example)

In most cases, checking for responses in setTimeout() every 3-5-10 seconds works just fine, and it's more efficient in terms of resources.

But there is a third option even better than that. Actually, long polling was more of a historical thing when there was nothing else to do to get realtime updates. Websockets are faster, inexpensive and now available in Django.

like image 188
Marat Avatar answered Sep 20 '22 23:09

Marat