问题
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