-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
195 lines (154 loc) · 5.59 KB
/
Copy pathmain.py
File metadata and controls
195 lines (154 loc) · 5.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
"""
AI-Dev-Insight 智能编程助手洞察平台 - FastAPI 后端应用入口
这是一个全自动化的AI编程工具信息聚合与决策支持平台的后端服务。
提供产品信息API、智能选择器、自动化数据采集等核心功能。
"""
import asyncio
import sys
# 修复Windows下Playwright的asyncio问题
if sys.platform == "win32":
asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())
from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError
from fastapi.staticfiles import StaticFiles
import uvicorn
from contextlib import asynccontextmanager
import logging
from config.config import settings
from config.logging import setup_logging
from config.middleware import RequestLoggingMiddleware, SecurityHeadersMiddleware
from api import products
from utils.response import APIResponseFormatter
from db.database import check_database_connection
# 导入Celery应用以确保任务被正确注册
from tasks.celery_app import celery_app
@asynccontextmanager
async def lifespan(app: FastAPI):
"""应用生命周期管理"""
# 启动时执行
setup_logging()
logger = logging.getLogger(__name__)
logger.info("🚀 AI-Dev-Insight Backend Starting...")
logger.info(f"📊 Environment: {settings.ENVIRONMENT}")
logger.info(f"🔗 Database URL: {settings.DATABASE_URL}")
# 检查数据库连接
if not check_database_connection():
logger.error("❌ Database connection failed!")
else:
logger.info("✅ Database connection successful")
yield
# 关闭时执行
logger.info("🛑 AI-Dev-Insight Backend Shutting down...")
# 创建FastAPI应用实例
app = FastAPI(
title="AI-Dev-Insight API",
description="智能编程助手洞察平台 - 后端API服务",
version="1.0.0",
docs_url="/docs",
redoc_url="/redoc",
lifespan=lifespan
)
# 添加自定义中间件
app.add_middleware(RequestLoggingMiddleware)
app.add_middleware(SecurityHeadersMiddleware)
# 配置CORS中间件
app.add_middleware(
CORSMiddleware,
allow_origins=settings.ALLOWED_ORIGINS,
allow_credentials=True,
allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
allow_headers=["*"],
)
# 挂载静态文件目录
import os
static_dir = os.path.join(os.path.dirname(__file__), "static")
os.makedirs(static_dir, exist_ok=True)
os.makedirs(os.path.join(static_dir, "uploads", "images"), exist_ok=True)
app.mount("/static", StaticFiles(directory=static_dir), name="static")
@app.get("/")
async def root():
"""根路径 - 健康检查"""
return {
"message": "AI-Dev-Insight Backend API",
"version": "1.0.0",
"status": "running",
"docs": "/docs"
}
@app.get("/health")
async def health_check():
"""健康检查端点"""
return {
"status": "healthy",
"environment": settings.ENVIRONMENT,
"timestamp": "2025-07-08T12:00:00Z"
}
# 注册API路由
app.include_router(products.router, prefix="/api/products")
# 导入并注册认证API路由
from api import auth
app.include_router(auth.router, prefix="/api")
# 导入并注册爬虫API路由
from api import crawl
app.include_router(crawl.router, prefix="/api/crawl")
# 导入并注册监控API路由
from api import monitoring
app.include_router(monitoring.router, prefix="/api")
# 导入并注册配置管理API路由
from api import config
app.include_router(config.router, prefix="/api")
# 导入并注册聊天API路由
from api import chat
app.include_router(chat.router, prefix="/api")
# 导入并注册文章管理API路由
from api import articles
app.include_router(articles.router, prefix="/api/articles")
@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
"""HTTP异常处理器"""
logger = logging.getLogger(__name__)
logger.warning(f"HTTP Exception: {exc.status_code} - {exc.detail}")
return JSONResponse(
status_code=exc.status_code,
content=APIResponseFormatter.error(
message=exc.detail,
status_code=exc.status_code
)
)
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
"""请求验证异常处理器"""
logger = logging.getLogger(__name__)
logger.warning(f"Validation Error: {exc.errors()}")
return JSONResponse(
status_code=422,
content=APIResponseFormatter.error(
message="请求数据验证失败",
error_code="VALIDATION_ERROR",
status_code=422,
details={"errors": exc.errors()}
)
)
@app.exception_handler(Exception)
async def general_exception_handler(request: Request, exc: Exception):
"""通用异常处理器"""
logger = logging.getLogger(__name__)
logger.error(f"Unhandled Exception: {type(exc).__name__}: {str(exc)}", exc_info=True)
return JSONResponse(
status_code=500,
content=APIResponseFormatter.error(
message="服务器内部错误",
error_code="INTERNAL_SERVER_ERROR",
status_code=500
)
)
if __name__ == "__main__":
print("Starting server...")
uvicorn.run(
"main:app",
host=settings.HOST,
port=settings.PORT,
reload=True,
log_level="info"
)