🔍 Code Extractor

function upload_file_to_filecloud

Maturity: 48

Uploads a file to FileCloud storage service, checking if the file already exists and comparing modification dates to determine if an update is needed.

File:
/tf/active/vicechatdev/mailsearch/upload_non_wuxi_coded.py
Lines:
63 - 154
Complexity:
moderate

Purpose

This function handles file uploads to a FileCloud server (filecloud.vicebio.com). It intelligently checks if a file already exists at the target location, compares modification timestamps to avoid redundant uploads, and automatically creates missing folders. It supports dry-run mode for testing and provides detailed console feedback about the upload process.

Source Code

def upload_file_to_filecloud(file_path, target_folder, s, cet_timezone, dry_run=False):
    """Upload a file to FileCloud"""
    ServerURL = 'https://filecloud.vicebio.com/'
    UploadEndPoint = 'core/upload'
    InfoEndpoint = 'core/fileinfo'
    
    filename = os.path.basename(file_path)
    path_in_fc = f"{target_folder}/{filename}"
    
    print(f"\n{filename}")
    
    if dry_run:
        print(f"  → Would upload to: {path_in_fc}")
        return True
    
    # Check if file exists in FileCloud
    ApiParams = {'file': path_in_fc}
    MoveCall = s.post(ServerURL + InfoEndpoint, params=ApiParams, cookies=s.cookies)
    doc = xmltodict.parse(MoveCall.text)
    
    # Get file modification time
    ti_m = os.path.getctime(file_path)
    file_date = datetime.fromtimestamp(ti_m, tz=cet_timezone).isoformat(timespec='seconds')
    
    if doc['fileinfo'] is None:
        # New file - upload
        print(f"  File doesn't exist in FileCloud - uploading...")
        UploadApiParams = {
            'appname': 'explorer',
            'path': target_folder,
            'date': file_date,
            'offset': 0
        }
        FileToUpload = {'file': open(file_path, 'rb')}
        
        try:
            UploadCall = s.post(ServerURL + UploadEndPoint, params=UploadApiParams, files=FileToUpload, cookies=s.cookies)
            
            if UploadCall.text == 'OK':
                print('  ✓ Upload successful')
                return True
            else:
                print(f'  ✗ Upload failed: {UploadCall.text}')
                
                if 'CLFC-01483' in UploadCall.text:
                    # Folder doesn't exist - create it
                    print("  Creating folder and retrying...")
                    create_folder(target_folder, s)
                    
                    FileToUpload = {'file': open(file_path, 'rb')}
                    UploadCall = s.post(ServerURL + UploadEndPoint, params=UploadApiParams, files=FileToUpload, cookies=s.cookies)
                    
                    if UploadCall.text == 'OK':
                        print('  ✓ Upload successful')
                        return True
                    else:
                        print(f'  ✗ Upload failed again: {UploadCall.text}')
                        return False
                return False
        finally:
            if 'file' in FileToUpload:
                FileToUpload['file'].close()
    else:
        # File exists - check if date is different
        fc_date = doc['fileinfo']['entry']['modifiediso'].split('+')[0]
        local_date = file_date.split('+')[0]
        
        if local_date == fc_date:
            print(f"  File exists with same date - skipping")
            return True
        else:
            print(f"  File exists with different date ({fc_date} vs {local_date}) - uploading new version...")
            UploadApiParams = {
                'appname': 'explorer',
                'path': target_folder,
                'date': file_date,
                'offset': 0
            }
            FileToUpload = {'file': open(file_path, 'rb')}
            
            try:
                UploadCall = s.post(ServerURL + UploadEndPoint, params=UploadApiParams, files=FileToUpload, cookies=s.cookies)
                
                if UploadCall.text == 'OK':
                    print('  ✓ Upload successful')
                    return True
                else:
                    print(f'  ✗ Upload failed: {UploadCall.text}')
                    return False
            finally:
                if 'file' in FileToUpload:
                    FileToUpload['file'].close()

Parameters

Name Type Default Kind
file_path - - positional_or_keyword
target_folder - - positional_or_keyword
s - - positional_or_keyword
cet_timezone - - positional_or_keyword
dry_run - False positional_or_keyword

Parameter Details

file_path: String path to the local file to be uploaded. Must be a valid file path that exists on the local filesystem.

target_folder: String path representing the destination folder in FileCloud where the file should be uploaded (e.g., '/documents/reports'). The folder will be created automatically if it doesn't exist.

s: A requests.Session object that must be authenticated with FileCloud. This session should have valid cookies for authentication with the FileCloud server.

cet_timezone: A ZoneInfo timezone object (typically ZoneInfo('CET')) used to format file modification timestamps in the correct timezone for FileCloud.

dry_run: Boolean flag (default: False). When True, the function only prints what would be uploaded without actually performing the upload operation.

Return Value

Returns a boolean value: True if the upload was successful, the file was skipped (same date), or dry_run mode is enabled; False if the upload failed for any reason (network error, permission issues, etc.).

Dependencies

  • os
  • requests
  • xmltodict
  • datetime
  • zoneinfo

Required Imports

import os
import requests
import xmltodict
from datetime import datetime
from zoneinfo import ZoneInfo

Usage Example

import os
import requests
import xmltodict
from datetime import datetime
from zoneinfo import ZoneInfo

# Create authenticated session (authentication code not shown)
session = requests.Session()
# Assume session is authenticated with FileCloud credentials

# Set up timezone
cet_tz = ZoneInfo('CET')

# Upload a file
file_to_upload = '/path/to/local/document.pdf'
target_location = '/shared/documents'

success = upload_file_to_filecloud(
    file_path=file_to_upload,
    target_folder=target_location,
    s=session,
    cet_timezone=cet_tz,
    dry_run=False
)

if success:
    print('File uploaded successfully')
else:
    print('Upload failed')

# Dry run example
upload_file_to_filecloud(
    file_path=file_to_upload,
    target_folder=target_location,
    s=session,
    cet_timezone=cet_tz,
    dry_run=True
)

Best Practices

  • Always use an authenticated requests.Session object with valid FileCloud credentials before calling this function
  • Ensure the create_folder() helper function is defined in the same module for automatic folder creation
  • Use dry_run=True first to verify the upload paths before performing actual uploads
  • The function automatically handles file handle cleanup using try-finally blocks to prevent resource leaks
  • File modification times are compared to avoid unnecessary uploads of unchanged files
  • The function uses os.path.getctime() which may return creation time on some systems instead of modification time; consider using os.path.getmtime() for true modification time
  • Error handling is built-in for missing folders (CLFC-01483 error code), which triggers automatic folder creation
  • The function prints detailed progress information to console, so consider redirecting output if running in a silent/background context
  • Session cookies must be maintained throughout the upload process for authentication

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function test_upload_modalities 75.8% similar

    Integration test function that validates FileCloud upload functionality by testing both new file creation and existing file update scenarios.

    From: /tf/active/vicechatdev/SPFCsync/test_upload_modalities.py
  • class FileCloudClient 65.5% 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
  • function test_filecloud_operations 64.5% similar

    Tests FileCloud basic operations by creating a test folder to verify connectivity and authentication with a FileCloud server.

    From: /tf/active/vicechatdev/SPFCsync/test_connections.py
  • function test_filecloud_connection 63.9% 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
  • function main_v98 63.0% similar

    Command-line application that uploads PDF files without WUXI coding from a local directory to a FileCloud server, with support for dry-run mode and customizable file patterns.

    From: /tf/active/vicechatdev/mailsearch/upload_non_wuxi_coded.py
← Back to Browse