This commit is contained in:
stardrophere
2026-03-09 18:13:35 +08:00
parent 3c57dd0cce
commit 5b541bbea3
11 changed files with 464 additions and 75 deletions
+44 -50
View File
@@ -1,71 +1,65 @@
# app/main.py
import os
from contextlib import asynccontextmanager
from fastapi import FastAPI, Depends
from sqlalchemy.orm import Session
from fastapi import FastAPI
from dotenv import load_dotenv
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from app.services.fetcher_service import fetch_and_save_trending_data
from app.database import engine
from app.models.models import Base
from app.database import engine, get_db
from app.models.models import Base, InfoSource, SourceType
# 路由总线
from app.api.router import api_router
load_dotenv()
CRAWL_INTERVAL = int(os.getenv("CRAWL_INTERVAL_MINUTES", 10))
scheduler = AsyncIOScheduler()
# ==========================================
# 1. 生命周期管理:App 启动时自动建表
# 1. 生命周期管理:App 启动时自动建表 & 启动调度器
# ==========================================
@asynccontextmanager
async def lifespan(app: FastAPI):
# 启动时执行:检查模型,如果表不存在,自动在 SQLite 中建表
# 1. 数据库建表
print("正在初始化数据库表...")
# ---> 核心修改 2:直接使用 Base,而不是 models.Base <---
Base.metadata.create_all(bind=engine)
print("数据库表初始化完成!")
yield
# 2. 配置并启动定时任务
scheduler.add_job(
fetch_and_save_trending_data,
'interval',
minutes=CRAWL_INTERVAL,
id='trending_fetch_job',
replace_existing=True
)
scheduler.start()
print(f"定时抓取任务已启动,每 {CRAWL_INTERVAL} 分钟执行一次")
# 为了测试方便,启动时立即执行一次
await fetch_and_save_trending_data()
yield # 此时 FastAPI 开始接受请求
# 3. 优雅关闭
scheduler.shutdown()
print("定时任务已安全关闭")
# 初始化 FastAPI,挂载生命周期
# 初始化 FastAPI
app = FastAPI(title="AI 新闻聚合引擎 API", lifespan=lifespan)
# ==========================================
# 2. 路由 API 定义
# 2. 挂载路由总线
# ==========================================
# 版本控制
app.include_router(api_router, prefix="/api/v1")
@app.get("/")
# 健康检查
@app.get("/", tags=["健康检查"])
async def root():
return {"message": "Welcome to AI News Aggregator API"}
@app.get("/hello/{name}")
async def say_hello(name: str):
return {"message": f"Hello {name}"}
# --->与数据库交互的真实接口
@app.post("/sources/")
async def create_info_source(name: str, url: str, db: Session = Depends(get_db)):
"""
测试接口:向数据库中添加一个新闻信息源
"""
# ---> 核心修改 3:直接使用 InfoSource 和 SourceType <---
new_source = InfoSource(
source_name=name,
source_type=SourceType.RSS_FEED, # 默认用 RSS 测试
home_url=url
)
db.add(new_source)
db.commit()
db.refresh(new_source) # 刷新以获取自动生成的 ID
return {"message": "创建成功!", "data": new_source}
@app.get("/sources/")
async def get_all_sources(db: Session = Depends(get_db)):
"""
测试接口:查询数据库中所有的信息源
"""
# ---> 核心修改 4:直接使用 InfoSource <---
sources = db.query(InfoSource).all()
return {"total": len(sources), "data": sources}
return {"message": "Welcome to AI News Aggregator API", "status": "ok"}