ETF_Suite_Portal/scripts/setup_vps.py
Pascal 1ff511ebe1 chore: Update project configuration and add setup scripts
- Update Docker and Caddy configuration

- Add VPS setup and secrets management scripts

- Add test suite

- Update documentation

- Clean up cache files
2025-05-27 14:41:58 +02:00

102 lines
3.7 KiB
Python

import os
import sys
import logging
from pathlib import Path
import subprocess
def setup_vps_environment():
"""Set up the environment for the ETF Portal on VPS."""
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
try:
# Get the FMP API key from user
fmp_api_key = input("Enter your FMP API key: ").strip()
if not fmp_api_key:
logger.error("❌ FMP API key is required")
return False
# Add to environment file
env_file = Path("/etc/environment")
if not env_file.exists():
env_file = Path.home() / ".bashrc"
# Check if key already exists
with open(env_file, 'r') as f:
content = f.read()
if f"FMP_API_KEY={fmp_api_key}" not in content:
with open(env_file, 'a') as f:
f.write(f'\n# ETF Portal Configuration\n')
f.write(f'export FMP_API_KEY="{fmp_api_key}"\n')
logger.info(f"✅ Added FMP_API_KEY to {env_file}")
else:
logger.info("✅ FMP_API_KEY already exists in environment file")
# Create cache directories
cache_dirs = [
Path("cache/FMP_cache"),
Path("cache/yfinance_cache")
]
for cache_dir in cache_dirs:
cache_dir.mkdir(parents=True, exist_ok=True)
cache_dir.chmod(0o755) # Owner can read/write/execute, others can read/execute
logger.info(f"✅ Cache directory created: {cache_dir}")
# Set up systemd service (if needed)
if input("Do you want to set up a systemd service for the ETF Portal? (y/n): ").lower() == 'y':
service_content = f"""[Unit]
Description=ETF Portal Streamlit App
After=network.target
[Service]
User={os.getenv('USER')}
WorkingDirectory={Path.cwd()}
Environment="FMP_API_KEY={fmp_api_key}"
ExecStart=/usr/local/bin/streamlit run ETF_Portal/pages/ETF_Analyzer.py
Restart=always
[Install]
WantedBy=multi-user.target
"""
service_path = Path("/etc/systemd/system/etf-portal.service")
if not service_path.exists():
with open(service_path, 'w') as f:
f.write(service_content)
logger.info("✅ Created systemd service file")
# Reload systemd and enable service
subprocess.run(["sudo", "systemctl", "daemon-reload"])
subprocess.run(["sudo", "systemctl", "enable", "etf-portal"])
logger.info("✅ Enabled ETF Portal service")
else:
logger.info("✅ Service file already exists")
return True
except Exception as e:
logger.error(f"❌ Setup failed: {str(e)}")
return False
if __name__ == "__main__":
print("🔧 ETF Portal VPS Setup")
print("======================")
print("This script will help you set up the ETF Portal on your VPS.")
print("Make sure you have your FMP API key ready.")
print()
success = setup_vps_environment()
if success:
print("\n✅ Setup completed successfully!")
print("\nNext steps:")
print("1. Source your environment file:")
print(" source /etc/environment # or source ~/.bashrc")
print("\n2. Run the test script to verify the configuration:")
print(" python -m ETF_Portal.tests.test_api_config")
print("\n3. If you set up the systemd service:")
print(" sudo systemctl start etf-portal")
print(" sudo systemctl status etf-portal # Check status")
else:
print("\n❌ Setup failed. Check the logs for details.")
sys.exit(1)