1.遇到问题
1-1.导出cvs文件乱码,解决办法:通过设置pycharm的文件编码为UTF-8
1-2.sonarqube提供的API接口,默认只展示第一页的100条数据,解决办法:经过测试,API接口每页最多展示500条数据,只支持20页展示,所以要对URL加参数细化结果,再通过翻页获取全部的数据,具体实现如下所示
2.最终生成的脚本
import csv
import json
import os
import requests
#SonarQube服务器的URL
sonar_url = "http://0.0.0.0:9000"
# SonarQube的用户凭证
sonar_login = "test"
sonar_password = "test@@111"
#项目键的列表
project_keys = ["matrix-platform","matrix-portal","Busi-data-platform","AICS_backend","AICS_frontend","CTC-OCR","drmp-frontend","drmp-backend","newcrm-sichuan","acct-cloud","rcsvue-zhejiang","rcsboot-zhejiang","so-app-sichuan","so-service-sichuan","ctc-trinitymis-app-repository","so-app-hebei","so-service-hebei"]
# 获取令牌
auth = (sonar_login, sonar_password)
# 设置CSV文件路径,没有路径则存储在对应项目的文件夹下
csv_file_path = "top_violations_report.csv"
n=0
# 打开CSV文件
with open(csv_file_path, 'w', newline='', encoding='utf-8') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['Project', 'type', 'Severity', 'Path', 'message'])
headers = {'Accept-Charset': 'utf-8'} # 指明接受的字符集
for project_key in project_keys:
a=0
# 获取项目的所有违规
url = f"{sonar_url}/api/issues/search?componentKeys={project_key}&severities=BLOCKER,CRITICAL"
response = requests.get(url, auth=auth,headers=headers)
print("总阻断严重违规数量:", response.json()['total'])
flag = int(response.json()['total']/500)+1
print("页码总数为:",flag)
# 因为sonarqube的API接口每页只能放500条,一共只能展示20页。所以结果要加具体的参数,并进行翻页才能获取所有的结果
for i in range(1,flag+1):
params = {
'p': i,
'ps': 500
}
response = requests.get(url, auth=auth, headers=headers,params=params)
issues = response.json()['issues']
#print("issues", issues)
for issue in issues:
writer.writerow([
project_key,
issue['type'],
issue['severity'],
issue['component'],
issue['message']
])
n=n+1
a=a+1
print("完成第",i,"页共",a,"条写入")
print(project_key,":阻断严重违规总条数:", n)
print("阻断严重违规总条数:", n)
3.执行效果和导出文件效果