function get_session_history
Flask API endpoint that retrieves the chat message history for the current user's session.
/tf/active/vicechatdev/docchat/app.py
950 - 957
simple
Purpose
This function serves as a REST API endpoint to fetch all chat messages associated with the current user's session. It checks for an active session ID, retrieves or creates the corresponding chat session, and returns the message history as JSON. This is typically used by frontend applications to display conversation history when a user returns to an active chat session or refreshes the page.
Source Code
def get_session_history():
"""Get chat history for current session"""
session_id = session.get('session_id')
if not session_id:
return jsonify({'messages': []})
chat_session = get_or_create_session(session_id)
return jsonify({'messages': chat_session.get('messages', [])})
Return Value
Returns a Flask JSON response object containing a dictionary with a 'messages' key. The value is either an empty list (if no session exists) or a list of message objects from the chat session. Each message object typically contains fields like 'role', 'content', 'timestamp', etc. The HTTP status code is 200 by default.
Dependencies
flaskuuidpathlibfunctoolsloggingdatetimethreadingwerkzeugjsonostimedocxreportlabiotraceback
Required Imports
from flask import Flask
from flask import jsonify
from flask import session
from functools import wraps
Conditional/Optional Imports
These imports are only needed under specific conditions:
import config
Condition: Required if get_or_create_session function depends on application configuration settings
Required (conditional)from auth.azure_auth import validate_azure_token
Condition: Required for the login_required decorator if using Azure SSO authentication
Required (conditional)Usage Example
# Client-side usage (JavaScript fetch example):
# fetch('/api/session/history', {
# method: 'GET',
# credentials: 'include',
# headers: {'Content-Type': 'application/json'}
# })
# .then(response => response.json())
# .then(data => console.log(data.messages));
# Server-side testing:
from flask import Flask, session
from flask.testing import FlaskClient
app = Flask(__name__)
app.secret_key = 'test-secret-key'
# Assuming the route is registered
with app.test_client() as client:
with client.session_transaction() as sess:
sess['session_id'] = 'test-session-123'
response = client.get('/api/session/history')
data = response.get_json()
print(data['messages']) # Prints message history
Best Practices
- Ensure the Flask session is properly configured with a secure SECRET_KEY in production
- The login_required decorator should be implemented to prevent unauthorized access to chat history
- Consider adding error handling for cases where get_or_create_session() might fail
- Implement rate limiting to prevent abuse of this endpoint
- Consider pagination if message history can grow very large
- Add logging for debugging session retrieval issues
- Validate session_id format before processing to prevent injection attacks
- Consider adding cache headers to control client-side caching behavior
- Ensure CORS is properly configured if the API is accessed from a different domain
- The get_or_create_session() function should handle thread-safety if using in-memory storage
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function get_history 93.6% similar
-
function api_get_chat_session_v1 82.2% similar
-
function api_get_chat_session 80.9% similar
-
function api_clear_chat_session 80.3% similar
-
function api_clear_history 79.4% similar