function save_config_to_file
Persists current application configuration values from the config module to a .env file, maintaining existing entries and formatting multi-value fields appropriately.
/tf/active/vicechatdev/docchat/app.py
284 - 322
moderate
Purpose
This function provides configuration persistence by writing runtime configuration values back to the .env file. It's designed for admin panel functionality where configuration changes need to be saved permanently. The function reads the existing .env file, updates specific configuration keys (SYSTEM_ROLE, SYSTEM_EXPERTISE, SYSTEM_DOMAIN_CONTEXT, CUSTOM_SYSTEM_INSTRUCTIONS, OUTPUT_STYLE, SUPPORTED_LANGUAGES), and writes them back while preserving proper formatting (quoting values with spaces, joining list values with delimiters).
Source Code
def save_config_to_file():
"""Save current config values to .env file for persistence"""
try:
env_file = config.BASE_DIR / '.env'
# Read existing .env
env_content = {}
if env_file.exists():
with open(env_file, 'r') as f:
for line in f:
line = line.strip()
if line and not line.startswith('#') and '=' in line:
key, value = line.split('=', 1)
env_content[key.strip()] = value.strip()
# Update values (keep quotes for multi-word values)
env_content['SYSTEM_ROLE'] = config.SYSTEM_ROLE
env_content['SYSTEM_EXPERTISE'] = '|'.join(config.SYSTEM_EXPERTISE) if isinstance(config.SYSTEM_EXPERTISE, list) else config.SYSTEM_EXPERTISE
env_content['SYSTEM_DOMAIN_CONTEXT'] = config.SYSTEM_DOMAIN_CONTEXT
env_content['CUSTOM_SYSTEM_INSTRUCTIONS'] = config.CUSTOM_SYSTEM_INSTRUCTIONS or ''
env_content['OUTPUT_STYLE'] = config.OUTPUT_STYLE
env_content['SUPPORTED_LANGUAGES'] = ','.join(config.SUPPORTED_LANGUAGES)
# Write back to .env file
with open(env_file, 'w') as f:
f.write("# DocChat Environment Configuration\n")
f.write("# Auto-updated by admin panel\n\n")
for key, value in env_content.items():
# Quote values that contain spaces
if ' ' in str(value) or '\n' in str(value):
f.write(f'{key}="{value}"\n')
else:
f.write(f"{key}={value}\n")
logger.info(f"✅ Configuration saved to {env_file}")
return True
except Exception as e:
logger.error(f"❌ Failed to save config to file: {e}")
return False
Return Value
Returns a boolean value: True if the configuration was successfully saved to the .env file, False if an exception occurred during the save operation. The function logs success/failure messages using the logger.
Dependencies
pathliblogging
Required Imports
from pathlib import Path
import logging
import config
Usage Example
import logging
from pathlib import Path
import config
# Setup logger (assumed to be in module scope)
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
# Ensure config module has required attributes
config.BASE_DIR = Path('/path/to/project')
config.SYSTEM_ROLE = 'AI Assistant'
config.SYSTEM_EXPERTISE = ['Python', 'Data Science']
config.SYSTEM_DOMAIN_CONTEXT = 'Technical documentation'
config.CUSTOM_SYSTEM_INSTRUCTIONS = 'Be helpful and concise'
config.OUTPUT_STYLE = 'Professional'
config.SUPPORTED_LANGUAGES = ['en', 'es', 'fr']
# Call the function to save configuration
success = save_config_to_file()
if success:
print('Configuration saved successfully')
else:
print('Failed to save configuration')
Best Practices
- Ensure the config module is properly initialized with all required attributes before calling this function
- The function automatically quotes values containing spaces or newlines to maintain .env file format compatibility
- List values in SYSTEM_EXPERTISE are joined with '|' delimiter, while SUPPORTED_LANGUAGES uses ',' delimiter
- The function preserves existing .env entries not managed by this function
- Proper error handling is included with logging, but callers should check the boolean return value
- The function creates a backup-style header comment in the .env file indicating auto-update
- File write operations are not atomic; consider implementing file locking for concurrent access scenarios
- Empty or None values for CUSTOM_SYSTEM_INSTRUCTIONS are saved as empty strings
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function load_config_v1 63.8% similar
-
function save_document_to_file 55.3% similar
-
function get_system_configuration 54.5% similar
-
function check_configuration_v1 54.0% similar
-
function load_env_file 53.9% similar