python 镜像仓库获取最新版本号

#/bin/python
# -*- coding: utf-8 -*-
import requests
from urllib import parse
from requests.auth import HTTPBasicAuth
import time
import json
import re

class HarborAapi(object):
def __init__(self,url,auth):
'''
@Author: xiajinqi
:param url:
'''
self.url = url
self.auth=auth
self.header = {
'User-Agent': 'User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36',
'Content-Type': 'application/json'
}



def setting(self):
###定义会话保持s并且设置s的auth 属性
self.session=requests.session()
self.session.auth=self.auth


###根据工程名字获取ID
def get_projects(self):
req_url = '%s/api/projects?page=1&page_size=15' % (self.url)
req_dict={
'page': '1',
'page_size': '15'
}
req_data=parse.urlencode(req_dict)
try:
r = self.session.get(req_url, data=req_dict, headers=self.header)
if r.status_code==200:
r.text
return r.text
except:
raise Exception('Input is error')
exit(0)


### 根据输入PEOJECTIC 和版本号查询对应的服务名字
def get_version_image(self,project_id,query):
req_url = '%s/api/repositories?project_id=%s&q=%s'% (self.url,project_id,query)
req_dict = {
'project_id':project_id ,
'q': query
}
req_data = parse.urlencode(req_dict)
print(req_dict)
try:
r = self.session.get(req_url, data=req_dict, headers=self.header)
if r.status_code == 200:
return r.text
except:
raise Exception('Input is error')
exit(0)


####根据服务名字获取最新镜像tag
def get_tags(self,q):
req_url = '%s/api/repositories/%s/tags?' % (self.url, q)
try:
r = self.session.get(req_url, headers=self.header)
if r.status_code == 200:
return r.text
except:
raise Exception('Input is error')
exit(0)




def main(url, auth):
project_name='test' ###工程名字
version='9.6.0' ####版本号
# start = time()
project_id=-1
tag_last=[]
try:
# begin开始
harbor = HarborAapi('xxxxxxxxx', auth)
harbor.setting()

#### 根据传入的project_name 获取 project_id
projects = json.loads(harbor.get_projects())
for i in range(0,len(projects)):
if projects[i]['name'] == project_name :
project_id=projects[i]['project_id']
break

#####
if project_id != -1:
print("根据project_id 和 version查找所需要的服务")
servcie_tags_list=json.loads(harbor.get_version_image(project_id,version))
find_res=''
if len(servcie_tags_list):

for i in range(0,len(servcie_tags_list)):
q=servcie_tags_list[i]['name']
tags_list= json.loads(harbor.get_tags(q))
###排序取最大
aa = []
for j in range(0,len(tags_list)):
tag = tags_list[j]['name']
if tags_list[j]['name'] !='latest':
aa.append(int(tag))

####获取最新版本号
aa.sort()
latest_version=aa[-1]
########## 获取服务名字 获取服务名字
service_name=re.split(r'(\d+)',str.split(q,'/')[1])[0]
tmp_service_latest_version=service_name+"="+str(latest_version)
find_res=find_res + tmp_service_latest_version+'\r\n'
print("""你今天需要发布的版本号:""")
print(find_res)


except:
# end = time()
# allTime = end - start
# traceback.print_exc()
print('输入信息不正确!')

if __name__ == '__main__':
auth = HTTPBasicAuth('admin', 'xxxxx')
url = 'xxxxxx'
main(url, auth)

posted @ 2020-07-27 09:40  马里亚纳仰望星空  Views(373)  Comments(0Edit  收藏  举报