function api_clear_history
Flask API endpoint that clears the chat history for the current user session by removing stored conversation data associated with the session ID.
/tf/active/vicechatdev/docchat/app.py
1286 - 1297
simple
Purpose
This endpoint provides a way for authenticated users to clear their chat history. It retrieves the session ID from the Flask session, calls a helper function to clear the associated chat data, and returns a success or error response. This is typically used when users want to start fresh conversations or remove their conversation history for privacy reasons.
Source Code
def api_clear_history():
"""Clear chat history"""
try:
session_id = session.get('session_id')
if session_id:
clear_session(session_id)
return jsonify({'message': 'Chat history cleared'})
except Exception as e:
logger.error(f"Error clearing history: {e}")
return jsonify({'error': str(e)}), 500
Return Value
Returns a Flask JSON response. On success, returns a JSON object with a 'message' key containing 'Chat history cleared' and HTTP status 200. On error, returns a JSON object with an 'error' key containing the error message string and HTTP status 500.
Dependencies
flasklogging
Required Imports
from flask import Flask
from flask import jsonify
from flask import session
import logging
Usage Example
# Client-side usage (JavaScript fetch example):
# fetch('/api/clear-history', {
# method: 'POST',
# headers: {
# 'Content-Type': 'application/json'
# },
# credentials: 'include'
# })
# .then(response => response.json())
# .then(data => console.log(data.message))
# .catch(error => console.error('Error:', error));
# Server-side setup required:
from flask import Flask, jsonify, session
import logging
from functools import wraps
app = Flask(__name__)
app.secret_key = 'your-secret-key'
logger = logging.getLogger(__name__)
# Define login_required decorator
def login_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if 'user_id' not in session:
return jsonify({'error': 'Unauthorized'}), 401
return f(*args, **kwargs)
return decorated_function
# Define clear_session helper function
def clear_session(session_id):
# Implementation to clear chat history from database/storage
pass
@app.route('/api/clear-history', methods=['POST'])
@login_required
def api_clear_history():
try:
session_id = session.get('session_id')
if session_id:
clear_session(session_id)
return jsonify({'message': 'Chat history cleared'})
except Exception as e:
logger.error(f'Error clearing history: {e}')
return jsonify({'error': str(e)}), 500
Best Practices
- Ensure the clear_session() function is properly implemented to handle database/storage cleanup
- The function gracefully handles cases where session_id might not exist in the session
- Always use HTTPS in production to protect session cookies
- Consider adding CSRF protection for POST endpoints
- Implement proper logging for audit trails when clearing user data
- Consider adding confirmation mechanisms before clearing history to prevent accidental data loss
- Ensure the login_required decorator properly validates user authentication
- Handle potential race conditions if multiple requests try to clear history simultaneously
- Consider implementing soft deletes instead of hard deletes for data recovery purposes
- Add rate limiting to prevent abuse of the endpoint
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function api_clear_chat_session 90.6% similar
-
function clear_session 84.7% similar
-
function get_history 81.3% similar
-
function api_clear_memory 80.3% similar
-
function get_session_history 79.4% similar