【问题标题】:TypeError: '<=' not supported between instances of 'int' and 's [duplicate]TypeError: \'<=\' 在 \'int\' 和 \'s [重复] 的实例之间不被支持
【发布时间】:2023-01-10 19:14:11
【问题描述】:

我正在使用一个函数从 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'

【问题讨论】:

  • “这是错误发生的地方:”好的,那么您是否尝试阅读并理解错误消息?你认为哪一行代码有错误?根据错误所说,您认为哪里出了问题?你认为 next_pagereq.headers["x-total-pages"] 的类型是什么? (你明白什么类型在编程中意味着什么?)
  • “出于某种原因,我需要在我的代码中的某处添加 int,但我不确定在哪里”好吧,我想它应该在错误发生的地方,对吧?什么更有意义:我们应该尝试将数字与数字进行比较,还是将字符串与字符串进行比较? (我假设你明白为什么比较一个数字和一个字符串是行不通的。)比较的哪一边似乎有数字,哪一边有字符串?那么,哪一方需要转换呢?如果你这样想通这个问题,究竟在迷惑什么?

标签: python function pagination gitlab-api


【解决方案1】:

我假设 req.headers["x-total-pages"] 是一个字符串,所以将它显式转换为 int,如下所示: int(req.headers["x-total-pages"]) 你应该没问题(因为你将比较两个 ints 而不是 intstr

【讨论】:

    猜你喜欢
    • 2022-11-20
    • 2023-04-08
    • 2020-09-07
    • 2018-09-03
    • 2020-11-13
    • 2021-01-15
    • 2020-06-02
    • 2019-08-14
    • 1970-01-01
    相关资源
    最近更新 更多