Search code examples
flask

Monitoring client activity with Flask


I have a page in Flask that will be requested by a client every couple of seconds, If the client doesn't request the page after couple of minutes I want to flag this client as disconnected and to run some code. I don't want to use web-sockets in this case. I was thinking of implementing this by creating a list of clients with 'last activity' variable that will be updated every time the client request the page, a thread will check the list every couple of minutes if the 'last activity' of the client is too old.

However I'm not sure it is the best and most efficient way of doing that without using web-sockets (maybe by using flask built-in code?).

Is it the best way? If not, Please share your suggestion for a better code design.

Thanks.


Solution

  • Your idea of using a list to track client activity and a separate thread to check for inactivity is a valid approach. However, you might want to use a Dictionary to Track Clients A dictionary can provide efficient lookups and updates for tracking client activity. The keys can be client identifiers, and the values can be timestamps of the last activity.

    Couple more tips:

    1. Use Background Scheduler Instead of a custom thread, you can use a scheduling library like APScheduler to periodically check for inactive clients. APScheduler is well-integrated with Flask and can handle periodic tasks efficiently.

    2. Use Flask's before_request and after_request Hooks These hooks can be used to update the client's last activity timestamp.

    Let me know if you need sample code for this.