如何使用Python访问Gerrit Rest API

3

首先,我对Gerrit的理解有限。

我正在尝试使用Python访问Gerrit Rest API,但无法成功。我想获取与账户相关的所有信息(提交,评审等)。

from requests.auth import HTTPDigestAuth
from pygerrit2 import GerritRestAPI, HTTPBasicAuth
auth = HTTPBasicAuth('user', 'password')
from pygerrit2 import GerritRestAPI
rest = GerritRestAPI(url='https://xxx.xx.xxx.xxx.com/', auth = auth)
changes = rest.get("changes/?q=is:open&q=is:close&q=all&o=DETAILED_ACCOUNTS&o=ALL_REVISIONS&o=ALL_COMMITS&o=ALL_FILES&o=MESSAGES", headers={'Content-Type': 'application/json'})

我得到的错误是:
ConnectionError: HTTPSConnectionPool(host='xxx.xx.xxx.xxx.com', port=443): Max retries exceeded with url: /login/a/changes/?q=is:open&q=is:close&q=all&o=DETAILED_ACCOUNTS&o=ALL_REVISIONS&o=ALL_COMMITS&o=ALL_FILES&o=MESSAGES (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x825bad0>: Failed to establish a new connection: [Errno 110] Connection timed out',))

如果我将查询复制粘贴到URL中,我就能获取信息,但是用Python却不能。该怎么办? 如果问题不清楚,请评论/编辑。 谢谢

2个回答

5
您遇到了来自requests库的连接错误(pygerrit2依赖于requests)- 这是由于您的连接超时导致的。为了避免这种情况,我建议使用像backoff这样的库。Backoff将捕获此连接错误并重试建立连接。这很容易通过装饰器和导入完成。
from requests.auth import HTTPDigestAuth
from pygerrit2 import GerritRestAPI, HTTPBasicAuth
import backoff
import requests

@backoff.on_exception(backoff.expo, 
                      requests.exceptions.ConnectionError,
                      max_time=10)
def makeGerritAPICall():
     auth = HTTPBasicAuth('user', 'password')
     rest = GerritRestAPI(url='https://xxx.xx.xxx.xxx.com/', auth = auth)
     changes = rest.get("changes/?q=is:open&q=is:close&q=all&o=DETAILED_ACCOUNTS&o=ALL_REVISIONS&o=ALL_COMMITS&o=ALL_FILES&o=MESSAGES", headers={'Content-Type': 'application/json'})

以下函数将在遇到ConnectionError时进行10秒的重试,然后失败并引发ConnectionError。我建议访问backoff git README文档,因为它们包含了关于backoff的大量有用信息。

我在这里是一个完全的初学者。我该如何打印我得到的changes变量的值? - Rahul Kumar

0
我遵循了@spencer.pinegar的建议。 您应该在执行请求的函数上方添加以下代码:
@backoff.on_exception(backoff.expo,
                      requests.exceptions.RequestException,
                      max_tries=8, max_time=60)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接