【Python】【应用】Python应用之玩转gerrit系列之一——搭建基础环境

1、缘起

  • Gerrit(Git)引入之后,经常要做些繁琐的工作,比如下载多个gerrit仓库,获取某次提交的代码对比、提交代码等。
  • Python是一个目前炙手可热的工具,用来对付这些繁琐的事情,刚刚好。
  • 2、准备工作

    2.1 安装python3

  • python2即将废弃,且对pip等支持较差,所以选择用python3。
  • 具体开发环境如下:
  • windows 7(64bits)
  • python 3.8.6
  • 按官方说明,python 2.6和2.7对接Pygerrit2更合适,而Python3处于试验阶段:
  • Pygerrit2 is compatible with Python 2.6 and Python 2.7. Support for
    Python 3 is experimental.

    2.2 安装相关库

  • requests库,提供了认证相关接口;
  • pygerrit2库,提供了gerrit相关的rest接口,不言而喻,以前有个pygerrit库的;
  • 安装方式见后文命令汇总,这里如不使用镜像库,安装可能比较慢。
  • 2.3 获取http的用户名和密码

  • 进入gerrit页面,登陆后,账号–>Setting–>http password可看到Username和http-password,
    也可直接进入页面:https://gerrit.zte.com.cn/#/settings/http-password查看。
  • 访问gerrit,有两种认证方式:http和ssh,pygerrit2仅支持http,所以这里仅获取http的账号和密码。
  • 具体如下图所示:
  • 3、牛刀小试

  • 下面仅以获取open状态的commit为例来说明,代码比较简单:
  • from requests.auth import HTTPDigestAuth
    from pygerrit2.rest import GerritRestAPI
    
    if __name__ == '__main__':
        auth = HTTPDigestAuth('qxhgd@xxx.com', 'pwd2qxhgd') #获取auth信息
        rest = GerritRestAPI(url='https://gerrit.xxx.com', auth=auth) #用auth信息去访问gerrit的rest接口
        changes = rest.get("/changes/?q=owner:self%20status:open") #用rest接口去查询相关信息,json格式返回
        print(changes) #将json串打印出来
    
  • 上述代码效果相当于,直接访问网址:
    https://gerrit.xxx.com/#/q/owner:qxhgd%2540xxx.com+status:open
    或在gerrit页面上输入下面过滤条件的结果。
  • 4、命令汇总

    python -m pip install --upgrade pip #升级pip
    pip3 install requests #直接使用官方源安装
    pip3 install -i https://pypi.douban.com/simple requests #使用镜像安装requests
    pip3 install pygerrit2-i https://pypi.douban.com/simple  #使用镜像安装pygerrit2, 用镜像安装可用上述两种格式
    

    5、参考资料

  • gerrit REST API官方文档
  • pygerrit2 github库
  • rest-api
  • pypi之pygerrit2
  • python官网
  • pygerrit
  • 如本文对你有些许帮助,欢迎打赏或通过里面链接购买书籍:
    支付宝打赏方式及我的购物小店

    来源:花神庙码农

    物联沃分享整理
    物联沃-IOTWORD物联网 » 【Python】【应用】Python应用之玩转gerrit系列之一——搭建基础环境

    发表评论