Lin / start_app.py
Zelyanoth's picture
Implement immediate Celery Beat schedule updates
1d6d1e6
raw
history blame
3.68 kB
#!/usr/bin/env python
"""
Entry point for the Lin application.
This script starts both the Flask application and Celery scheduler components.
"""
import os
import sys
import subprocess
import platform
import time
from pathlib import Path
def check_redis():
"""Check if Redis is running."""
try:
import redis
client = redis.Redis(host='localhost', port=6379, db=0)
client.ping()
print("βœ“ Redis connection successful")
return True
except Exception as e:
print(f"βœ— Redis connection failed: {e}")
print("Please start Redis server first:")
print(" Windows: redis-server")
print(" Linux/Mac: sudo systemctl start redis")
return False
def start_celery_components():
"""Start Celery worker and beat scheduler in background processes."""
print("Starting Celery components...")
backend_dir = Path(__file__).parent / "backend"
# Start Celery worker
worker_cmd = [
sys.executable, "-m", "celery",
"-A", "celery_config",
"worker",
"--loglevel=info",
"--pool=solo",
"--max-tasks-per-child=100"
]
# Start Celery beat
beat_cmd = [
sys.executable, "-m", "celery",
"-A", "celery_config",
"beat",
"--loglevel=info",
"--scheduler=django_celery_beat.schedulers:DatabaseScheduler"
]
if platform.system() == "Windows":
# Windows: Use subprocess to start background processes
subprocess.Popen(worker_cmd, cwd=backend_dir,
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
creationflags=subprocess.CREATE_NEW_PROCESS_GROUP)
subprocess.Popen(beat_cmd, cwd=backend_dir,
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
creationflags=subprocess.CREATE_NEW_PROCESS_GROUP)
else:
# Linux/Mac: Use subprocess with proper signal handling
subprocess.Popen(worker_cmd, cwd=backend_dir,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
subprocess.Popen(beat_cmd, cwd=backend_dir,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print("Celery worker and beat scheduler started in background")
time.sleep(2) # Give Celery components time to start
if __name__ == "__main__":
# Set the port for Hugging Face Spaces
port = os.environ.get('PORT', '7860')
os.environ.setdefault('PORT', port)
print(f"Starting Lin application on port {port}...")
print("=" * 60)
# Check if Redis is available
if not check_redis():
print("Warning: Redis not available. Celery may not function properly.")
print("Continuing with Flask app only...")
print("=" * 60)
try:
# Start Celery components first
start_celery_components()
# Import and run the backend Flask app directly
from backend.app import create_app
app = create_app()
print("=" * 60)
print("Flask application starting...")
print("Access the application at:")
print(f" http://localhost:{port}")
print(f" http://127.0.0.1:{port}")
print("=" * 60)
app.run(
host='0.0.0.0',
port=int(port),
debug=False,
threaded=True
)
except KeyboardInterrupt:
print("\nShutting down application...")
sys.exit(0)
except Exception as e:
print(f"Failed to start Lin application: {e}")
import traceback
traceback.print_exc()
sys.exit(1)