function api_folders
Flask API endpoint that returns a hierarchical JSON tree structure of all folders (excluding files) within the configured document folder, used for folder selection in upload interfaces.
/tf/active/vicechatdev/docchat/app.py
1153 - 1193
moderate
Purpose
This endpoint provides a complete folder hierarchy for the document storage system, enabling UI components to display folder trees for navigation and file upload destination selection. It recursively traverses the document folder structure, filtering out hidden folders, system folders (__pycache__), and files, returning only the folder structure in a nested JSON format suitable for tree view components.
Source Code
def api_folders():
"""Get full folder tree (folders only, no files) for upload folder selection"""
try:
if not config.DOCUMENT_FOLDER.exists():
return jsonify({
'type': 'folder',
'name': 'qa_docs',
'path': '',
'children': []
})
def build_folder_tree(path, relative_base=""):
"""Recursively build folder tree (folders only)"""
folders = []
try:
for entry in sorted(path.iterdir(), key=lambda x: x.name.lower()):
if entry.is_dir() and not entry.name.startswith('.') and entry.name != '__pycache__':
relative_path = f"{relative_base}/{entry.name}" if relative_base else entry.name
folder_item = {
'type': 'folder',
'name': entry.name,
'path': relative_path,
'children': build_folder_tree(entry, relative_path)
}
folders.append(folder_item)
except PermissionError:
pass
return folders
result = {
'type': 'folder',
'name': 'qa_docs',
'path': '',
'children': build_folder_tree(config.DOCUMENT_FOLDER, '')
}
return jsonify(result)
except Exception as e:
logger.error(f"Error getting folders: {e}")
return jsonify({'error': str(e)}), 500
Return Value
Returns a Flask JSON response containing a nested dictionary structure representing the folder tree. The root object has keys: 'type' (always 'folder'), 'name' (always 'qa_docs'), 'path' (empty string for root), and 'children' (array of nested folder objects with the same structure). Each child folder includes its relative path from the root. On error, returns a JSON object with an 'error' key and HTTP status 500.
Dependencies
flaskpathliblogging
Required Imports
from flask import jsonify
from pathlib import Path
import logging
import config
Usage Example
# Assuming Flask app setup and config module exists
# config.py
from pathlib import Path
DOCUMENT_FOLDER = Path('./qa_docs')
# app.py
from flask import Flask, jsonify
import logging
import config
app = Flask(__name__)
logger = logging.getLogger(__name__)
@app.route('/api/folders', methods=['GET'])
def api_folders():
# ... function code ...
pass
# Client-side usage (JavaScript fetch example):
# fetch('/api/folders')
# .then(response => response.json())
# .then(data => {
# console.log(data);
# // Example output:
# // {
# // type: 'folder',
# // name: 'qa_docs',
# // path: '',
# // children: [
# // {type: 'folder', name: 'subfolder1', path: 'subfolder1', children: []},
# // {type: 'folder', name: 'subfolder2', path: 'subfolder2', children: [...]}
# // ]
# // }
# });
Best Practices
- The function gracefully handles missing document folders by returning an empty tree structure
- Hidden folders (starting with '.') and __pycache__ directories are automatically filtered out
- PermissionError exceptions are caught and ignored during directory traversal to prevent crashes
- Folder names are sorted case-insensitively for consistent ordering
- Relative paths are built incrementally to maintain correct folder hierarchy
- All exceptions are logged and return proper HTTP 500 error responses
- The function only returns folders, not files, making it suitable for folder selection UIs
- Ensure config.DOCUMENT_FOLDER is properly configured before calling this endpoint
- Consider implementing caching for large folder structures to improve performance
- The endpoint requires proper Flask app context and should be protected with authentication if needed
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function api_document_tree 84.1% similar
-
function api_index_folder 61.4% similar
-
function create_folder 61.4% similar
-
function api_upload 61.1% similar
-
function build_document_tree_recursive 60.7% similar