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

Gitlab API分页获取用户遇类型错误:int与str无法比较求助

GitLab API分页获取用户的类型错误解决方法

问题描述

我用函数从GitLab API获取用户,希望通过响应头实现分页以存储全部用户(而非仅单页100条),但代码中出现类型错误,不清楚该在何处添加int转换,请求协助:

原代码:

# Base URI of Gitlab API from our private Gitlab Instance
baseuri = "https://git.tools.dev.mycompany.net/api/v4"

# Function to grab users and put objects in S3 bucket:
def get_gitlab_users(access_token=access_token, baseuri=baseuri):
    next_page = 1
    result = []
    headers = {
        "Content-Type": "application/json",
        "Authorization": "Bearer {}".format(access_token),
    }

    # Paginate by using x-total-pages from the headers received in the response
    # https://docs.gitlab.com/ee/api/#pagination-link-header
    url = f"{baseuri}/users/?per_page=100&active=true&without_project_bots=true&page={next_page}"
    req = http.request(method="GET", url=url, headers=headers)
    result.extend(json.loads(req.data))

    while next_page <= req.headers["x-total-pages"]:
        url = f"{baseuri}/users/?per_page=100&active=true&without_project_bots=true&page={next_page}"
        req = http.request(method="GET", url=url, headers=headers)
        result.extend(json.loads(req.data))

错误信息:

while next_page <= req.headers["x-total-pages"]:
TypeError: '<=' not supported between instances of 'int' and 'str'

解决方法

错误核心是响应头返回的x-total-pages是字符串类型,无法直接和整数类型的next_page比较,同时原代码的分页逻辑还有重复请求、无限循环的问题,一起修正如下:

修正后的完整代码

# Base URI of Gitlab API from our private Gitlab Instance
baseuri = "https://git.tools.dev.mycompany.net/api/v4"

# Function to grab users and put objects in S3 bucket:
def get_gitlab_users(access_token=access_token, baseuri=baseuri):
    next_page = 1
    result = []
    headers = {
        "Content-Type": "application/json",
        "Authorization": "Bearer {}".format(access_token),
    }

    # 获取第一页数据及总页数
    url = f"{baseuri}/users/?per_page=100&active=true&without_project_bots=true&page={next_page}"
    req = http.request(method="GET", url=url, headers=headers)
    result.extend(json.loads(req.data))
    
    # 将响应头中的总页数转换为整数
    total_pages = int(req.headers["x-total-pages"])
    
    # 从第2页开始循环请求直到最后一页
    next_page += 1
    while next_page <= total_pages:
        url = f"{baseuri}/users/?per_page=100&active=true&without_project_bots=true&page={next_page}"
        req = http.request(method="GET", url=url, headers=headers)
        result.extend(json.loads(req.data))
        # 页码递增,避免无限循环
        next_page += 1
    
    return result  # 返回全量用户列表,方便后续处理

关键修改点

  • 单独提取total_pages并通过int()转换为整数类型,解决类型比较错误
  • 循环前先将next_page加1,避免重复请求第一页数据
  • 循环内部每次递增next_page,确保页码逐步推进至总页数,防止无限循环

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 11:50:21