🔍 Code Extractor

function get_file_list

Maturity: 44

Retrieves a list of files and directories from a FileCloud server at a specified path by making an authenticated API request and parsing the XML response.

File:
/tf/active/vicechatdev/UQchat/download_uq_files.py
Lines:
44 - 67
Complexity:
moderate

Purpose

This function interfaces with a FileCloud server API to fetch directory listings. It handles the HTTP request, parses the XML response using xmltodict, and normalizes the output to always return a list of entries. It includes error handling for failed requests and empty directories, making it suitable for file system traversal and content discovery operations in FileCloud environments.

Source Code

def get_file_list(session, path):
    """Get list of files and directories in a path"""
    info_endpoint = 'core/getfilelist'
    params = {'path': path}
    
    response = session.post(FILECLOUD_URL + info_endpoint, params=params, cookies=session.cookies)
    
    if response.status_code != 200:
        print(f"✗ Failed to get file list for {path}")
        return []
    
    doc = xmltodict.parse(response.text)
    
    # Handle case where there are no entries
    if doc.get('entries') is None or doc['entries'].get('entry') is None:
        return []
    
    entries = doc['entries']['entry']
    
    # Ensure entries is always a list
    if not isinstance(entries, list):
        entries = [entries]
    
    return entries

Parameters

Name Type Default Kind
session - - positional_or_keyword
path - - positional_or_keyword

Parameter Details

session: A requests.Session object that maintains authentication state and cookies for making authenticated API calls to the FileCloud server. Must be pre-configured with valid authentication credentials.

path: A string representing the path on the FileCloud server to list contents from. Should be a valid FileCloud path (e.g., '/folder/subfolder'). Can be root path or nested directory path.

Return Value

Returns a list of dictionaries, where each dictionary represents a file or directory entry with metadata from the FileCloud API. Returns an empty list ([]) if the request fails (non-200 status), if the path is empty, or if there are no entries. When a single entry exists, it's normalized to a list containing that one entry. The structure of each entry dictionary depends on the FileCloud API response format.

Dependencies

  • requests
  • xmltodict

Required Imports

import requests
import xmltodict

Usage Example

import requests
import xmltodict

# Define the FileCloud server URL
FILECLOUD_URL = 'https://filecloud.example.com/'

# Create and authenticate session
session = requests.Session()
# Assume authentication is done here (login endpoint call)
# session.post(FILECLOUD_URL + 'core/login', data={'username': 'user', 'password': 'pass'})

# Get file list from root directory
files = get_file_list(session, '/')
for entry in files:
    print(f"Name: {entry.get('name')}, Type: {entry.get('type')}")

# Get file list from specific folder
subfolder_files = get_file_list(session, '/documents/reports')
if not subfolder_files:
    print('No files found or access denied')
else:
    print(f'Found {len(subfolder_files)} entries')

Best Practices

  • Always ensure the session object is properly authenticated before calling this function to avoid 401/403 errors
  • Check if the returned list is empty to distinguish between an empty directory and a failed request (consider checking response status separately if needed)
  • The FILECLOUD_URL global variable must be defined in the same scope or imported from a configuration module
  • Handle potential network errors by wrapping calls in try-except blocks for requests.exceptions
  • Be aware that xmltodict.parse may raise exceptions for malformed XML responses
  • The function normalizes single entries to a list, so always iterate over the result as a list
  • Consider implementing rate limiting or caching for repeated calls to the same path to reduce server load

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function check_filecloud_structure 59.2% similar

    Diagnostic function that checks the FileCloud server structure and verifies accessibility of various paths including root, SHARED, and configured base paths.

    From: /tf/active/vicechatdev/SPFCsync/check_filecloud_structure.py
  • function create_folder_v1 58.9% similar

    Creates a nested folder structure on a FileCloud server by traversing a path and creating missing directories.

    From: /tf/active/vicechatdev/filecloud_wuxi_sync.py
  • function test_filecloud_connection 58.4% similar

    Tests the connection to a FileCloud server by establishing a client connection and performing a document search operation to verify functionality.

    From: /tf/active/vicechatdev/contract_validity_analyzer/test_implementation.py
  • class FileCloudClient_v1 58.4% similar

    A client class for interacting with FileCloud storage systems through direct API calls, providing authentication, file search, download, and metadata retrieval capabilities.

    From: /tf/active/vicechatdev/contract_validity_analyzer/utils/filecloud_client.py
  • class FileCloudClient 57.4% similar

    A client class for interacting with FileCloud server API, providing authentication, file management, folder creation, and file upload capabilities.

    From: /tf/active/vicechatdev/SPFCsync/filecloud_client.py
← Back to Browse