function get_user_email
Retrieves the email address of the currently authenticated user from the Flask session object.
/tf/active/vicechatdev/vice_ai/complex_app.py
521 - 523
simple
Purpose
This function provides a safe way to access the current user's email address stored in the Flask session. It's designed to work within a Flask web application context where user authentication information is stored in the session. The function returns 'unknown' as a fallback if the user data or email is not present in the session, preventing KeyError exceptions.
Source Code
def get_user_email():
"""Get current user email"""
return session.get('user', {}).get('email', 'unknown')
Return Value
Returns a string containing the user's email address if available in the session under session['user']['email']. If the 'user' key doesn't exist in the session, or if the 'email' key doesn't exist within the user dictionary, returns the string 'unknown' as a default value.
Dependencies
flask
Required Imports
from flask import session
Usage Example
from flask import Flask, session
app = Flask(__name__)
app.secret_key = 'your-secret-key-here'
def get_user_email():
"""Get current user email"""
return session.get('user', {}).get('email', 'unknown')
@app.route('/profile')
def profile():
# Assuming user is logged in and session is populated
email = get_user_email()
return f'User email: {email}'
# Example with session data
with app.test_request_context():
with app.test_client() as client:
with client.session_transaction() as sess:
sess['user'] = {'email': 'user@example.com'}
email = get_user_email()
print(email) # Output: user@example.com
Best Practices
- Always call this function within a Flask request context to avoid RuntimeError
- Ensure the Flask application has a SECRET_KEY configured for session management
- Handle the 'unknown' return value appropriately in calling code
- Consider implementing proper authentication middleware to ensure session['user'] is populated before calling this function
- For production use, consider adding logging when 'unknown' is returned to track authentication issues
- This function assumes a specific session structure (session['user']['email']); ensure your authentication system follows this pattern
- Consider adding type hints for better code documentation: def get_user_email() -> str:
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function get_user_id 91.1% similar
-
function get_current_user 86.7% similar
-
function get_user_name 82.9% similar
-
function get_current_user_id 73.7% similar
-
function get_current_username 72.0% similar