data init idk other stuff
This commit is contained in:
79
app/main.py
79
app/main.py
@ -1,4 +1,4 @@
|
||||
from fastapi import FastAPI
|
||||
from fastapi import FastAPI, HTTPException
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from fastapi.responses import FileResponse
|
||||
@ -6,15 +6,17 @@ from contextlib import asynccontextmanager
|
||||
import uvicorn
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
from app.routes import routes
|
||||
from app.db.database import init_db, SessionLocal
|
||||
from app.services.service_manager import ServiceManager
|
||||
import logging
|
||||
|
||||
# Configure logging
|
||||
log_file = "app.log"
|
||||
if os.path.exists(log_file):
|
||||
os.remove(log_file) # Remove existing log file to start fresh
|
||||
log_file = Path("app.log")
|
||||
if log_file.exists():
|
||||
# Archive old log file instead of deleting
|
||||
archive_path = log_file.with_suffix(f'.{log_file.stat().st_mtime}.log')
|
||||
log_file.rename(archive_path)
|
||||
|
||||
# Create a formatter
|
||||
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(name)s - %(message)s')
|
||||
@ -37,27 +39,47 @@ logger = logging.getLogger(__name__)
|
||||
logger.info("Application starting up...")
|
||||
|
||||
# Initialize service manager
|
||||
service_manager = ServiceManager()
|
||||
service_manager = None
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
global service_manager
|
||||
service_manager = ServiceManager()
|
||||
|
||||
# Startup
|
||||
init_db()
|
||||
logger.info("Database initialized successfully")
|
||||
|
||||
# Initialize all services
|
||||
await service_manager.initialize_services()
|
||||
|
||||
# Start the scheduler
|
||||
scheduler = service_manager.get_service('scheduler')
|
||||
await scheduler.start_scheduled_tasks()
|
||||
logger.info("Scheduler started successfully")
|
||||
|
||||
yield
|
||||
|
||||
# Shutdown
|
||||
await service_manager.cleanup_services()
|
||||
logger.info("All services cleaned up successfully")
|
||||
try:
|
||||
init_db()
|
||||
logger.info("Database initialized successfully")
|
||||
|
||||
# Initialize all services
|
||||
await service_manager.initialize_services()
|
||||
|
||||
# Get a database session
|
||||
db = SessionLocal()
|
||||
try:
|
||||
data_init_service = service_manager.get_service('data_initialization')
|
||||
data_init = await data_init_service.initialize_data(db, game_ids=[1, 3], use_cache=False, init_categories=False, init_products=False, init_groups=False, init_archived_prices=True, init_mtgjson=False, archived_prices_start_date="2024-03-05", archived_prices_end_date="2025-04-17")
|
||||
logger.info(f"Data initialization results: {data_init}")
|
||||
|
||||
# Start the scheduler
|
||||
scheduler = service_manager.get_service('scheduler')
|
||||
await scheduler.start_scheduled_tasks(db)
|
||||
logger.info("Scheduler started successfully")
|
||||
|
||||
yield
|
||||
except Exception as e:
|
||||
logger.error(f"Error during application startup: {str(e)}")
|
||||
raise
|
||||
finally:
|
||||
db.close()
|
||||
except Exception as e:
|
||||
logger.error(f"Critical error during application startup: {str(e)}")
|
||||
raise
|
||||
finally:
|
||||
# Shutdown
|
||||
if service_manager:
|
||||
await service_manager.cleanup_services()
|
||||
logger.info("All services cleaned up successfully")
|
||||
|
||||
app = FastAPI(
|
||||
title="CCR Cards Management API",
|
||||
@ -72,16 +94,23 @@ app.mount("/static", StaticFiles(directory="app/static"), name="static")
|
||||
# Serve index.html at root
|
||||
@app.get("/")
|
||||
async def read_root():
|
||||
return FileResponse('app/static/index.html')
|
||||
index_path = Path('app/static/index.html')
|
||||
if not index_path.exists():
|
||||
raise HTTPException(status_code=404, detail="Index file not found")
|
||||
return FileResponse(index_path)
|
||||
|
||||
# Serve app.js
|
||||
@app.get("/app.js")
|
||||
async def read_app_js():
|
||||
return FileResponse('app/static/app.js')
|
||||
js_path = Path('app/static/app.js')
|
||||
if not js_path.exists():
|
||||
raise HTTPException(status_code=404, detail="App.js file not found")
|
||||
return FileResponse(js_path)
|
||||
|
||||
# Configure CORS with specific origins in production
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_origins=["http://localhost:3000"], # Update with your frontend URL
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
|
Reference in New Issue
Block a user