function get_current_username
Retrieves the current user's username from Flask-Login's current_user object or falls back to the Flask session, returning 'anonymous' if neither is available.
/tf/active/vicechatdev/docchat/blueprint.py
42 - 49
simple
Purpose
This function provides a unified way to get the current user's identifier in a Flask web application. It first attempts to retrieve the username from Flask-Login's authentication system (preferring email over name), and if that fails or the user is not authenticated, it falls back to checking the Flask session. This is useful for logging, auditing, or displaying user information when you need to handle both authenticated and unauthenticated users gracefully.
Source Code
def get_current_username():
"""Get current username from Flask-Login or session"""
try:
if current_user and current_user.is_authenticated:
return current_user.email or current_user.name
except:
pass
return session.get('username', 'anonymous')
Return Value
Returns a string representing the current user's identifier. This will be: (1) the user's email if available from Flask-Login's current_user, (2) the user's name if email is not available but name is, (3) the 'username' value from the Flask session if current_user is not authenticated or unavailable, or (4) the string 'anonymous' if none of the above are available. Type: str
Dependencies
flaskflask-login
Required Imports
from flask import session
from flask_login import current_user
Usage Example
from flask import Flask, session
from flask_login import LoginManager, current_user
app = Flask(__name__)
app.secret_key = 'your-secret-key'
login_manager = LoginManager()
login_manager.init_app(app)
def get_current_username():
"""Get current username from Flask-Login or session"""
try:
if current_user and current_user.is_authenticated:
return current_user.email or current_user.name
except:
pass
return session.get('username', 'anonymous')
@app.route('/profile')
def profile():
username = get_current_username()
return f'Current user: {username}'
if __name__ == '__main__':
with app.test_request_context():
session['username'] = 'guest_user'
print(get_current_username()) # Output: 'guest_user' or user email/name if authenticated
Best Practices
- This function must be called within a Flask request context, otherwise accessing 'session' or 'current_user' will raise an error
- The broad exception handling (bare except) may hide important errors; consider logging exceptions or using more specific exception types in production code
- Ensure Flask-Login is properly configured with a user_loader callback before relying on current_user
- The function prioritizes email over name; ensure this matches your application's user identification requirements
- Consider adding type hints for better code documentation: def get_current_username() -> str:
- For security-sensitive operations, verify that 'anonymous' users have appropriate access restrictions
- If using this for logging or auditing, consider adding additional context like IP address or timestamp
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function get_current_user 84.2% similar
-
function get_current_user_id 83.8% similar
-
function get_user_name 79.1% similar
-
function get_user_id 73.2% similar
-
function get_user_email 72.0% similar