function index_v4
Flask route handler for the root URL ('/') that redirects authenticated users to the document workspace and unauthenticated users to the login page.
/tf/active/vicechatdev/vice_ai/complex_app.py
634 - 638
simple
Purpose
Serves as the entry point/landing page for the Flask web application. It performs authentication checking and routes users to the appropriate page based on their authentication status. This is a common pattern in web applications to protect resources and provide a seamless user experience by automatically directing users to the correct destination.
Source Code
def index():
"""Main page"""
if is_authenticated():
return redirect(url_for('document_workspace'))
return redirect(url_for('login'))
Return Value
Returns a Flask redirect response object. If the user is authenticated (is_authenticated() returns True), redirects to the 'document_workspace' route. If not authenticated, redirects to the 'login' route. The redirect uses Flask's url_for() function to generate URLs dynamically based on route names.
Dependencies
flask
Required Imports
from flask import redirect
from flask import url_for
Usage Example
from flask import Flask, redirect, url_for, session
app = Flask(__name__)
app.secret_key = 'your-secret-key'
def is_authenticated():
return 'user_id' in session
@app.route('/')
def index():
"""Main page"""
if is_authenticated():
return redirect(url_for('document_workspace'))
return redirect(url_for('login'))
@app.route('/login')
def login():
return 'Login Page'
@app.route('/document_workspace')
def document_workspace():
return 'Document Workspace'
if __name__ == '__main__':
app.run(debug=True)
Best Practices
- Ensure is_authenticated() function is properly implemented and handles edge cases (expired sessions, invalid tokens, etc.)
- The function relies on external route definitions ('document_workspace' and 'login') - ensure these routes exist before deploying
- Consider adding error handling for cases where url_for() might fail if routes are not defined
- This pattern should be used consistently across the application for protected routes
- Consider implementing rate limiting or CSRF protection for authentication-related routes
- Ensure Flask session configuration is secure (secure cookies, httponly flags) when using session-based authentication
- The function has no explicit error handling - consider wrapping in try-except if is_authenticated() might raise exceptions
Tags
Similar Components
AI-powered semantic similarity - components with related functionality: