2024-12-31 22:27:04 +08:00
|
|
|
from fastapi import FastAPI
|
|
|
|
from fastapi.middleware.cors import CORSMiddleware
|
2025-03-04 20:36:52 +08:00
|
|
|
from fastapi.staticfiles import StaticFiles
|
|
|
|
import os
|
|
|
|
from pathlib import Path
|
|
|
|
|
2025-01-03 17:06:40 +08:00
|
|
|
from mooc.db.database import init_db
|
2024-12-31 22:27:04 +08:00
|
|
|
from mooc.api.v1.api import api_router
|
|
|
|
from mooc.core.config import settings
|
2025-03-04 20:36:52 +08:00
|
|
|
from mooc.core.logger import setup_logging, get_logger
|
2024-12-31 22:27:04 +08:00
|
|
|
|
|
|
|
app = FastAPI(
|
|
|
|
title="ExamService",
|
|
|
|
description="题库小程序服务端API",
|
|
|
|
version="1.0.0"
|
|
|
|
)
|
|
|
|
|
2025-03-04 20:36:52 +08:00
|
|
|
# 初始化日志系统
|
|
|
|
setup_logging(app)
|
|
|
|
logger = get_logger(__name__)
|
|
|
|
|
2024-12-31 22:27:04 +08:00
|
|
|
# CORS设置
|
|
|
|
app.add_middleware(
|
|
|
|
CORSMiddleware,
|
|
|
|
allow_origins=["*"],
|
|
|
|
allow_credentials=True,
|
|
|
|
allow_methods=["*"],
|
|
|
|
allow_headers=["*"],
|
|
|
|
)
|
2025-01-03 17:06:40 +08:00
|
|
|
|
2024-12-31 22:27:04 +08:00
|
|
|
# 初始化数据库
|
|
|
|
init_db()
|
2025-03-04 20:36:52 +08:00
|
|
|
logger.info("Database initialized")
|
|
|
|
|
|
|
|
# 确保上传目录存在
|
|
|
|
upload_dir = settings.UPLOAD_IMG_DIR
|
|
|
|
if not os.path.isabs(upload_dir):
|
|
|
|
# 获取当前工作目录
|
|
|
|
base_dir = os.path.dirname(os.path.abspath(__file__))
|
|
|
|
upload_dir = os.path.join(base_dir, upload_dir.lstrip('/'))
|
|
|
|
|
|
|
|
os.makedirs(upload_dir, exist_ok=True)
|
|
|
|
logger.info(f"Static files directory: {upload_dir}")
|
|
|
|
|
|
|
|
# 挂载静态文件目录
|
|
|
|
# 注意:这里的'/attachment'必须与你在URL中使用的路径一致
|
|
|
|
app.mount("/attachment", StaticFiles(directory=upload_dir), name="attachment")
|
2024-12-31 22:27:04 +08:00
|
|
|
|
|
|
|
app.include_router(api_router, prefix=settings.API_V1_STR)
|
2025-03-04 20:36:52 +08:00
|
|
|
logger.info(f"API routes registered with prefix: {settings.API_V1_STR}")
|
2024-12-31 22:27:04 +08:00
|
|
|
|
|
|
|
@app.get("/")
|
|
|
|
async def root():
|
2025-03-04 20:36:52 +08:00
|
|
|
return {"message": f"Welcome to {settings.PROJECT_NAME} API"}
|
2024-12-31 22:27:04 +08:00
|
|
|
|
|
|
|
if __name__ == '__main__':
|
2025-03-04 20:36:52 +08:00
|
|
|
logger.info("Starting server...")
|
|
|
|
uvicorn.run('main:app', host='0.0.0.0', port=2333, reload=True, workers=1)
|