function download_file_v1
Downloads a single file from a FileCloud server using an authenticated session and saves it to a local path with streaming support.
/tf/active/vicechatdev/UQchat/download_uq_files.py
70 - 107
moderate
Purpose
This function facilitates file downloads from FileCloud cloud storage by making an authenticated POST request to the FileCloud API download endpoint. It handles the download in chunks to efficiently manage memory usage for large files, automatically creates parent directories if they don't exist, and provides error handling with status feedback. The function is designed to work within a larger FileCloud integration system where session management and authentication are handled externally.
Source Code
def download_file(session, remote_path, local_path):
"""Download a single file from FileCloud"""
download_endpoint = 'core/downloadfile'
# Extract filename from remote path
filename = remote_path.split('/')[-1]
params = {
'filepath': remote_path,
'filename': filename
}
try:
response = session.post(
FILECLOUD_URL + download_endpoint,
params=params,
cookies=session.cookies,
stream=True
)
if response.status_code == 200:
# Ensure parent directory exists
local_path.parent.mkdir(parents=True, exist_ok=True)
# Write file
with open(local_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
if chunk:
f.write(chunk)
return True
else:
print(f" ✗ Download failed: {response.status_code}")
return False
except Exception as e:
print(f" ✗ Error: {e}")
return False
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
session |
- | - | positional_or_keyword |
remote_path |
- | - | positional_or_keyword |
local_path |
- | - | positional_or_keyword |
Parameter Details
session: A requests.Session object that contains authentication cookies and maintains connection state with the FileCloud server. This session must be pre-authenticated before calling this function.
remote_path: String representing the full path to the file on the FileCloud server (e.g., '/folder/subfolder/file.txt'). The function extracts the filename from this path by splitting on '/' and taking the last element.
local_path: A pathlib.Path object specifying where the downloaded file should be saved on the local filesystem. Parent directories will be created automatically if they don't exist.
Return Value
Returns a boolean value: True if the file was successfully downloaded and saved (HTTP 200 response), False if the download failed due to HTTP errors or exceptions. Error messages are printed to stdout but not returned.
Dependencies
requestspathlib
Required Imports
import requests
from pathlib import Path
Usage Example
import requests
from pathlib import Path
# Define the FileCloud base URL (required global variable)
FILECLOUD_URL = 'https://filecloud.example.com/'
# Create and authenticate session (authentication logic not shown)
session = requests.Session()
# ... perform authentication to populate session.cookies ...
# Define paths
remote_file = '/MyFolder/documents/report.pdf'
local_file = Path('./downloads/report.pdf')
# Download the file
success = download_file(session, remote_file, local_file)
if success:
print('File downloaded successfully')
else:
print('Download failed')
Best Practices
- Ensure the session object is properly authenticated before calling this function, as it relies on session cookies for authorization
- Use pathlib.Path objects for local_path to ensure cross-platform compatibility
- The function uses streaming (stream=True) and chunked downloads (8192 bytes) to handle large files efficiently without loading them entirely into memory
- Parent directories are created automatically, but ensure you have write permissions for the target location
- The function prints error messages to stdout; consider capturing or logging these in production environments
- The FILECLOUD_URL global variable must end with a trailing slash or be properly formatted to concatenate with the endpoint
- Error handling is basic; consider wrapping calls in additional try-except blocks for production use
- The function extracts filename from remote_path using simple string splitting, which may not handle edge cases like trailing slashes
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
class FileCloudClient_v1 66.1% similar
-
function _download_current_version 65.5% similar
-
class FileCloudClient 62.8% similar
-
function download_model 62.5% similar
-
function login_filecloud 61.5% similar