Logout View
Logging out means removing the user id from the session.
Flask-Login provides:
logout_user()
flowchart LR A["POST /logout"] --> B["logout_user()"] B --> C["remove user_id from the session"] B --> D["clear the remember-me cookie"] C --> E["current_user is anonymous"] D --> E E --> F["redirect to a public page"] F --> G["the next request has no identity"]
Example
Section titled “Example”from flask import redirect, url_for
from flask_login import logout_user, login_required
@app.route("/logout")
@login_required
def logout():
logout_user()
return redirect(url_for("home"))Why protect logout with login_required?
Section titled “Why protect logout with login_required?”It’s not strictly required, but:
- it keeps behavior consistent
- it avoids confusion when anonymous users hit
/logout
UX note
Section titled “UX note”It’s common to flash a message:
- “You’ve been logged out.”
And redirect to home.
pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading