How to get the list of users who are currently logged in Flask-Login?

妖精的绣舞 提交于 2020-06-09 05:27:28

问题


In my Flask-SQLAlchemy web application I have implemented Flask-Login for user authentication and authorization. Now I am building an Admin section where the admin user can add, edit or delete any user and view user list. So before deleting any user I want to know whether that user is currently logged in to the application from somewhere or simply having any active session with the web application. How can I accomplice this? Or Is this even possible in the application level?

[Note: As you can see, this is NOT about current_user.is_authenticated]


回答1:


You will have to implement this feature yourself as there is not a way to do it natively with flask-login.

I can think of myriad ways to do this, but the quickest is probably just keeping track of the last time a user accessed your site. Then you can set a reasonable timeout where you assume the user is not logged in if they haven't done anything for the last 30 minutes (or however long you feel comfortable with)

For example:

@app.before_request
def update_last_active():
    current_user.last_active = datetime.utcnow()
    db.session.commit()

This would update User.last_active every time the user sends a request to your server.



来源:https://stackoverflow.com/questions/58918154/how-to-get-the-list-of-users-who-are-currently-logged-in-flask-login

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!