SatCat commited on
Commit
d58f064
·
verified ·
1 Parent(s): 3a86f2d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +16 -99
app.py CHANGED
@@ -1,110 +1,27 @@
1
- import os
2
- import json
3
- import httpx
4
- from fastapi import FastAPI, HTTPException, APIRouter
5
- from datetime import datetime, timedelta
6
- from fastapi.middleware.cors import CORSMiddleware
7
- from fastmcp.server import FastMCP
8
  from contextlib import asynccontextmanager
9
- from typing import List, Dict, Optional
10
 
11
- # 初始化 MCP 服务器(必须在 FastAPI 之前)
12
- mcp_server = FastMCP(name="GitHubTrendingAPI")
 
 
13
 
14
  @asynccontextmanager
15
  async def lifespan(app: FastAPI):
16
- await fetch_github_trending()
 
17
  yield
 
18
 
19
  app = FastAPI(lifespan=lifespan)
20
 
21
- # CORS 配置
22
- app.add_middleware(
23
- CORSMiddleware,
24
- allow_origins=["*"],
25
- allow_credentials=True,
26
- allow_methods=["*"],
27
- allow_headers=["*"],
28
- )
29
-
30
- # 缓存变量
31
- cached_trending = []
32
- last_updated = None
33
-
34
- async def fetch_github_trending():
35
- global cached_trending, last_updated
36
- headers = {"Accept": "application/vnd.github.v3+json"}
37
- if token := os.getenv("GITHUB_TOKEN"):
38
- headers["Authorization"] = f"token {token}"
39
-
40
- try:
41
- async with httpx.AsyncClient() as client:
42
- r = await client.get(
43
- "https://api.github.com/search/repositories",
44
- params={"q": "stars:>1000", "sort": "stars", "per_page": 10},
45
- headers=headers
46
- )
47
- r.raise_for_status()
48
- cached_trending = [
49
- {
50
- "name": repo["full_name"],
51
- "url": repo["html_url"],
52
- "stars": repo["stargazers_count"]
53
- }
54
- for repo in r.json()["items"]
55
- ]
56
- last_updated = datetime.now()
57
- except Exception as e:
58
- print(f"Fetch error: {e}")
59
- if not cached_trending:
60
- raise HTTPException(500, "Failed to fetch data")
61
-
62
- @mcp_server.tool()
63
- async def get_trending_repos(num: int = 10) -> dict:
64
- if not last_updated or (datetime.now() - last_updated) > timedelta(minutes=30):
65
- await fetch_github_trending()
66
- return {"trending": cached_trending[:num]}
67
-
68
- # 关键修改:正确挂载MCP路由
69
- # 方案1:直接挂载整个MCP应用
70
- app.mount("/mcp", mcp_server.http_app())
71
-
72
- # 方案2:或者使用APIRouter(如果方案1不行)
73
- # mcp_router = APIRouter()
74
- # mcp_router.include_router(mcp_server.http_app().router, prefix="")
75
- # app.include_router(mcp_router, prefix="/mcp")
76
-
77
- # 添加MCP健康检查路由
78
- @app.get("/mcp/health")
79
- async def mcp_health_check():
80
- return {"status": "ok", "mcp_version": "1.0"}
81
 
82
  @app.get("/")
83
- async def root():
84
- # 添加更多有用的调试信息
85
- return {
86
- "message": "API is running",
87
- "endpoints": {
88
- "mcp_tool": "/mcp/tool/get_trending_repos",
89
- "mcp_schema": "/mcp/schema",
90
- "mcp_health": "/mcp/health",
91
- "trending": "/trending"
92
- }
93
- }
94
-
95
- @app.get("/trending")
96
- async def get_trending(num: int = 10):
97
- if not cached_trending:
98
- await fetch_github_trending()
99
- return {"trending": cached_trending[:num]}
100
-
101
- # 在app.py中添加
102
- @app.get("/mcp/")
103
- async def mcp_root():
104
- return {
105
- "message": "MCP API root",
106
- "endpoints": {
107
- "tools": "/mcp/tool",
108
- "schema": "/mcp/schema"
109
- }
110
- }
 
1
+ import time
2
+ import datetime
 
 
 
 
 
3
  from contextlib import asynccontextmanager
 
4
 
5
+ from fastapi import FastAPI
6
+ from fastapi_utilities import repeat_every, repeat_at
7
+
8
+ my_data = ['Ready?', 'Go!', ]
9
 
10
  @asynccontextmanager
11
  async def lifespan(app: FastAPI):
12
+ # --- startup ---
13
+ test()
14
  yield
15
+ # --- shutdown ---
16
 
17
  app = FastAPI(lifespan=lifespan)
18
 
19
+ @repeat_at(cron="* * * * *")
20
+ def work():
21
+ now_dtime = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')
22
+ my_data.append(now_dtime)
23
+ my_data.pop(0) # trim old values
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
  @app.get("/")
26
+ def read_root():
27
+ return {"my_data": my_data}