function _download_current_version
Downloads the current version of a document from either FileCloud storage or standard storage, handling different storage types and triggering a browser download.
/tf/active/vicechatdev/document_controller_backup.py
2427 - 2481
moderate
Purpose
This method is part of a document management system that handles downloading document versions. It checks the storage type of the current document version (FileCloud or standard), retrieves the document content from the appropriate storage backend, and triggers a browser download using Panel's download API. It provides user feedback through a notification area and handles various error conditions including missing documents, storage failures, and network issues.
Source Code
def _download_current_version(self, event=None):
"""Download the current document version"""
if not self.current_version:
self.notification_area.object = "**Error:** No document version available"
return
try:
# Get version UID
version_uid = self.current_version.get('UID')
# Check if this is a FileCloud stored document
storage_type = self.current_version.get('storage_type', '')
if storage_type == 'FILECLOUD':
# Get the file from FileCloud
from CDocs.controllers.filecloud_controller import download_document_from_filecloud
# Show downloading message
self.notification_area.object = "Downloading document from FileCloud..."
doc_content = download_document_from_filecloud(
user=self.user,
document_uid=self.document_uid
)
# Handle response correctly based on what download_document_from_filecloud returns
if isinstance(doc_content, bytes):
# Direct bytes content
file_data = io.BytesIO(doc_content)
file_name = self.current_version.get('file_name', 'document.pdf')
pn.state.execute_download(file_data, filename=file_name)
self.notification_area.object = "Document downloaded successfully"
elif isinstance(doc_content, dict) and doc_content.get('success') == False:
self.notification_area.object = f"**Error:** {doc_content.get('message', 'Could not download document')}"
else:
self.notification_area.object = "**Error:** Could not download document from FileCloud"
else:
# Try to use the standard document controller method
from CDocs.controllers.document_controller import download_document_version
doc_content = download_document_version(version_uid)
if doc_content and 'content' in doc_content:
# Create BytesIO object for download
file_data = io.BytesIO(doc_content['content'])
file_name = self.current_version.get('file_name', 'document.pdf')
# Use Panel's API to trigger download
pn.state.execute_download(file_data, filename=file_name)
self.notification_area.object = "Document downloaded successfully"
else:
self.notification_area.object = "**Error:** Could not download document"
except Exception as e:
logger.error(f"Error downloading document: {e}")
self.notification_area.object = f"**Error:** {str(e)}"
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
self |
- | - | positional_or_keyword |
event |
- | None | positional_or_keyword |
Parameter Details
self: Instance reference to the containing class. Expected to have attributes: current_version (dict with document metadata including UID, storage_type, file_name), notification_area (Panel object for displaying messages), user (DocUser instance for authentication), and document_uid (string identifier for the document).
event: Optional event parameter typically passed by Panel UI callbacks when the method is triggered by a button click or similar user interaction. Defaults to None and is not used in the function body.
Return Value
Returns None. The function performs side effects: triggers a browser download via pn.state.execute_download() and updates self.notification_area.object with status messages. On success, downloads the file to the user's browser. On failure, displays error messages in the notification area.
Dependencies
paneliologgingCDocs
Required Imports
import io
import panel as pn
import logging
Conditional/Optional Imports
These imports are only needed under specific conditions:
from CDocs.controllers.filecloud_controller import download_document_from_filecloud
Condition: only when storage_type is 'FILECLOUD'
Required (conditional)from CDocs.controllers.document_controller import download_document_version
Condition: only when storage_type is not 'FILECLOUD' (standard storage)
Required (conditional)Usage Example
# This method is typically used as part of a Panel-based document viewer class
# Example class context:
class DocumentViewer:
def __init__(self, user, document_uid):
self.user = user
self.document_uid = document_uid
self.notification_area = pn.pane.Markdown('')
self.current_version = {
'UID': 'version-123',
'storage_type': 'FILECLOUD',
'file_name': 'document_v1.pdf'
}
# Create download button
self.download_btn = pn.widgets.Button(
name='Download',
button_type='primary'
)
self.download_btn.on_click(self._download_current_version)
def _download_current_version(self, event=None):
# ... (the provided function code) ...
pass
# Usage:
viewer = DocumentViewer(user=current_user, document_uid='doc-456')
# User clicks download button, which triggers _download_current_version
# Or manually trigger:
viewer._download_current_version()
Best Practices
- Ensure Panel server is running before calling this method as it relies on pn.state.execute_download()
- Always check that self.current_version is populated before calling this method
- Handle the notification_area updates appropriately in the UI to provide user feedback
- Ensure proper error logging is configured to capture exceptions
- The method assumes self.user has appropriate permissions to download the document
- For FileCloud storage, ensure FileCloud integration is properly configured with valid credentials
- The method handles both bytes and dict responses from download_document_from_filecloud, ensure the controller returns appropriate types
- Consider implementing rate limiting or download quotas for production use
- The method uses io.BytesIO for in-memory file handling, which may not be suitable for very large files
- Ensure the logger variable is defined at module level before using this method
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function _view_document 85.7% similar
-
function download_document_version 67.8% similar
-
function get_document_download_url 64.6% similar
-
function convert_document_to_pdf 52.9% similar
-
function create_document_v1 51.9% similar