Spaces:
Sleeping
Sleeping
Download main.py from paperplane22/Notiproxy: direct link, hf CLI and curl.
- Browser
- Download file 2.95 kB
-
https://huggingface.co/spaces/paperplane22/Notiproxy/resolve/main/main.py
- Command line
-
hf download hf://spaces/paperplane22/Notiproxy/main.py
-
curl -L -o main.py https://huggingface.co/spaces/paperplane22/Notiproxy/resolve/main/main.py
2.95 kB
| """FastAPI 应用主入口(Hugging Face 兼容) | |
| - 读取系统环境变量以及 .env(由 Pydantic Settings 完成) | |
| - 在 Hugging Face Spaces(Docker)环境下按 $PORT 暴露服务 | |
| """ | |
| # main.py | |
| import logging | |
| import os | |
| from contextlib import asynccontextmanager | |
| from typing import Optional | |
| from fastapi import FastAPI, Request, HTTPException, Depends, Header | |
| from fastapi.responses import JSONResponse, StreamingResponse | |
| from app.core.config import settings | |
| from app.providers.notion_provider import NotionAIProvider | |
| logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') | |
| # 根据 DEV_MODE 动态设置日志级别(默认 INFO;DEV 为 DEBUG) | |
| _level = logging.DEBUG if getattr(settings, "DEV_MODE", False) else logging.INFO | |
| logging.getLogger().setLevel(_level) | |
| for _n in ("uvicorn", "uvicorn.error", "uvicorn.access"): | |
| logging.getLogger(_n).setLevel(_level) | |
| logger = logging.getLogger(__name__) | |
| provider = NotionAIProvider() | |
| async def lifespan(app: FastAPI): | |
| logger.info(f"应用启动中... {settings.APP_NAME} v{settings.APP_VERSION}") | |
| logger.info("服务已配置为 Notion AI 代理模式。") | |
| # 在 Hugging Face Spaces 上,平台会通过环境变量 PORT 告知监听端口 | |
| # 本地/其他环境下未设置 PORT 时,回退到 NGINX_PORT 仅用于提示显示 | |
| display_port = os.getenv("PORT", str(settings.NGINX_PORT)) | |
| logger.info(f"服务将在 http://localhost:{display_port} 上可用") | |
| yield | |
| logger.info("应用关闭。") | |
| app = FastAPI( | |
| title=settings.APP_NAME, | |
| version=settings.APP_VERSION, | |
| description=settings.DESCRIPTION, | |
| lifespan=lifespan | |
| ) | |
| async def verify_api_key(authorization: Optional[str] = Header(None)): | |
| if settings.API_MASTER_KEY and settings.API_MASTER_KEY != "1": | |
| if not authorization or "bearer" not in authorization.lower(): | |
| raise HTTPException(status_code=401, detail="需要 Bearer Token 认证。") | |
| token = authorization.split(" ")[-1] | |
| if token != settings.API_MASTER_KEY: | |
| raise HTTPException(status_code=403, detail="无效的 API Key。") | |
| async def chat_completions(request: Request) -> StreamingResponse: | |
| try: | |
| request_data = await request.json() | |
| return await provider.chat_completion(request_data) | |
| except Exception as e: | |
| logger.error(f"处理聊天请求时发生顶层错误: {e}", exc_info=True) | |
| raise HTTPException(status_code=500, detail=f"内部服务器错误: {str(e)}") | |
| async def list_models(): | |
| return await provider.get_models() | |
| def root(): | |
| return {"message": f"欢迎来到 {settings.APP_NAME} v{settings.APP_VERSION}. 服务运行正常。"} | |