title: How to logout a user from the database with flask-login
body: <p>I have a web application made with python/flask, and I use flask-login to authenticate users. In the user interface a user can logout. But the user can also be logged out by the database (when a session expires, or when the user expires).</p>
  
  <p>My user loader looks like this:</p>
  
  <pre><code>@login_manager.user_loader
  def user_loader(id):
      user = SessionUser.find_by_session_id(id) #hits the database
      if user is None:
          flash('You have been automatically logged out')
          #flask_login.logout_user() #RecursionError: maximum recursion depth exceeded
          session['user_id'] = None
      return user
  </code></pre>
  
  <p>When the database can't find the <code>id</code>, I want the user to be logged out. Reasons are: there is no need to hit the <code>SessionUser.find_by_session_id</code>-call more than once if an <code>id</code> can't be found. Also, I want show a message the user has been logged out (and I only want to show this once). Finally, when a user is logged out of the database, I want to user the unauthenticated templates.</p>
  
  <p>If I don't have the <code>if user is None:</code> code, the user loader it hit with every request. There are two problems with this:</p>
  
  <ol>
  <li>I can't flash the message "You have been automatically logged out" (because it will keep on showing)</li>
  <li>There is an unnecessary database hit.</li>
  </ol>
  
  <p>I fixed this by clearing the session-variable <code>user_id</code>, but this is an unwanted solution, since it users the internals of <code>flask_login</code>, not an API.</p>
  
  <p>What would be the best approach?</p>