You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python分页处理:FastAPI对接GitHub API并存储至MongoDB

FastAPI 集成GitHub API 并存储数据到MongoDB实现方案

需求概述

  • 分页从GitHub API拉取所有用户数据
  • 为每个用户分页拉取其所有仓库数据
  • 将拉取到的用户、仓库数据持久化存储到MongoDB

现有异步实现代码(基于httpx)

分页拉取GitHub用户列表

async def fetch_users_from_github(per_page=10):
    page = 1
    users = []
    while True:
        url = f"{GITHUB_API_URL}/users?per_page={per_page}&page={page}"
        headers = {"Authorization": f"token {GITHUB_TOKEN}"}
        async with httpx.AsyncClient() as client:
            response = await client.get(url, headers=headers)
            response.raise_for_status()
            data = response.json()
            if not data:
                break
            users.extend(data)
            page += 1
    return users

分页拉取指定用户的仓库列表

async def fetch_repos_from_github(username, per_page=10):
    page = 1
    repos = []
    while True:
        url = f"{GITHUB_API_URL}/users/{username}/repos?per_page={per_page}&page={page}"
        headers = {"Authorization": f"token {GITHUB_TOKEN}"}
        async with httpx.AsyncClient() as client:
            response = await client.get(url, headers=headers)
            response.raise_for_status()
            data = response.json()
            if not data:
                break
            repos.extend(data)
            page += 1
    return repos

拉取并存储用户及仓库数据的主逻辑

async def fetch_and_store_users_and_repos():
    users = await fetch_users_from_github()
    for user in users:
        save_user(user)
        repos = await fetch_repos_from_github(user["login"])
        save_repos(repos)

可优化方向

  1. 复用httpx客户端:当前每个请求都创建新的httpx.AsyncClient,建议在函数外部初始化客户端并复用,减少连接建立的开销
  2. 并发获取仓库:当前串行遍历用户拉取仓库,可使用asyncio.gather实现并发请求,大幅提升整体拉取效率
  3. 批量存储数据:避免单条数据频繁写入MongoDB,积累一定数量后批量插入,降低数据库IO压力
  4. 处理GitHub API速率限制:GitHub API有请求频率限制,需添加速率控制逻辑——检查响应头的X-RateLimit-Remaining和X-RateLimit-Reset字段,在达到限制时等待重置后再继续请求
  5. 完善异常处理:当前仅用raise_for_status处理HTTP错误,可补充网络超时、JSON解析失败、MongoDB存储失败等场景的异常捕获与容错逻辑

内容的提问来源于stack exchange,提问作者Gal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 12:01:07