python-jenkins:调用get_version()提示
2018-08-24 本文已影响0人
Xpitz
欢迎关注我的微信公众号:「阿拉平平」
报错说明
首先贴一下自己写的脚本:
# -*- coding: utf-8 -*-
import jenkins
class JenkinsAPI:
"""
Installing:
pip install python-jenkins
Import:
import jenkins
"""
def __init__(self):
self.url = 'http://127.0.0.1:8080/'
self.username = 'admin'
self.password = 'admin'
self.server = self._connect()
def _connect(self):
return jenkins.Jenkins(self.url, username=self.username, password=self.password)
def get_version(self):
"""get jenkins version"""
print(self.server.get_version())
if __name__ == '__main__':
jenkins_obj = JenkinsAPI()
jenkins_obj.get_version()
执行脚本报错如下:
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "test.py", line 30, in <module>
jenkins_obj.get_version()
File "test.py", line 25, in get_version
print(self.server.get_version())
File "/data/temp_venv/lib/python3.6/site-packages/jenkins/__init__.py", line 812, in get_version
% self.server)
jenkins.BadHTTPException: Error communicating with server[http://127.0.0.1:8080/]
解决方法
方法一:修改Jenkins的全局安全设置
如图所示:勾选 匿名用户具有可读权限
选项即可
方法二:在代码中加入一个认证方法
在_init_()方法中,加上了self.server.get_whoami()
由于该方法能够有认证信息,所以再调用get_verson()
就可以获取到
def __init__(self):
self.url = 'http://127.0.0.1:8080/'
self.username = 'admin'
self.password = 'admin'
self.server = self._connect()
self.server.get_whoami()
方法三:修改源码
源码位置在:site-packages/jenkins/__init__.py
,找到get_version方法,代码从
def get_version(self):
try:
request = requests.Request('GET', self._build_url(''))
request.headers['X-Jenkins'] = '0.0'
response = self._response_handler(self._request(request))
return response.headers['X-Jenkins']
except (req_exc.HTTPError, BadStatusLine):
raise BadHTTPException("Error communicating with server[%s]"
% self.server)
改为:
def get_version(self):
try:
self._maybe_add_auth() # 添加这句即可
request = requests.Request('GET', self._build_url(''))
request.headers['X-Jenkins'] = '0.0'
response = self._response_handler(self._request(request))
return response.headers['X-Jenkins']
except (req_exc.HTTPError, BadStatusLine):
raise BadHTTPException("Error communicating with server[%s]"
% self.server)
写在后面
当时在网上搜索的时候,发现这篇博客也记录了这个问题,这里贴下地址:
Jenkins: BadHTTPException: Error communicating with server
之后我查看了一下模块的源码,发现代码有所差异。我本地安装的是1.1.0,而博客中使用的应该是0.4的版本,修改方法并不适用高版本。
抽空又看了下源码,已补上修改源码的方法。