Skip to content
Advertisement

How to achieve realtime updates on my website (with Flask)?

I am using Flask and I want to show the user how many visits that he has on his website in realtime.

Currently, I think a way is to, create an infinite loop which has some delay after every iteration and which makes an ajax request getting the current number of visits.

I have also heard about node.js however I think that running another process might make the computer that its running on slower (i’m assuming) ?

How can I achieve the realtime updates on my site? Is there a way to do this with Flask?

Thank you in advance!

Advertisement

Answer

Well, there are many possibilites:

1) Polling – this is exactly what you’ve described. Infinite loop which makes an AJAX request every now and then. Easy to implement, can be easily done with Flask however quite inefficient – eats lots of resources and scales horribly – making it a really bad choice (avoid it at all costs). You will either kill your machine with it or the notification period (polling interval) will have to be so big that it will be a horrible user experience.

2) Long polling – a technique where a client makes an AJAX request but the server responds to that request only when a notification is available. After receiving the notification the client immediately makes a new request. You will require a custom web server for this – I doubt it can be done with Flask. A lot better then polling (many real websites use it) but could’ve been more efficient. That’s why we have now:

3) WebSockets – truely bidirectional communication. Each client maintains an open TCP connection with the server and can react to incoming data. But again: requires a custom server plus only the most modern browsers support it.

4) Other stuff like Flash or Silverlight or other HTTP tricks (chunked encoding): pretty much the same as no 3). Though more difficult to maintain.

So as you can see if you want something more elegant (and efficient) than polling it requires some serious preparation.

As for processes: you should not worry about that. It’s not about how many processes you use but how heavy they are. 1 badly written process can easily kill your machine while 100 well written will work smoothly. So make sure it is written in such a way that it won’t freeze your machine (and I assure you that it can be done up to some point defined by number of simultaneous users).

As for language: it doesn’t matter whether this is Node.js or any other language (like Python). Pick the one you are feeling better with. However I am aware that there’s a strong tendency to use Node.js for such projects and thus there might be more proper libraries out there in the internets. Or maybe not. Python has for example Twisted and/or Tornado specially for that (and probably much much more).

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement