Python调用sonar API操作实战

需求

当Django项目遇见了调用第三方接口时,有很多方式对接,今天介绍持续集成系统与sonarqube系统对接操作实战,小试牛刀,先杀只鸡,慢慢的后面杀牛。

方案

接口模块开头
# -*- coding: utf-8 -*-
import requests # http请求模块
from django.conf import settings # 导入settings模块里面的配置信息
from urllib.parse import urljoin # url解析模块
import logging # 日志模块

logger = logging.getLogger(__name__) #设置日志

init调用
#此处的方法__init__()是一个特殊的方法,每当你根据类创建新实例时, Python都会自动运行它。在这个方法的名称中,开头和末尾各有两个下划线,这是一种约定,旨在避免Python默认方法与普通方法发生名称冲突
    def __init__(self):
        self.urls = settings.SONAR_URL # sonar 地址
        self.token = settings.SONAR_TOKEN # sonar token信息,主要用于连接sonar,类似username和password登陆调用
        self.session = requests.Session() # 会话模块
        self.session.auth = self.token, '' # 登陆
拼接url
    def set_url(self, url):
        try:
            return urljoin(self.urls, url)
        except Exception as e:
            return None

请求调用操作
    def func_call(self, urls, method, **data):
        """"""
        # 获取方法和调用
        try:
            call = getattr(self.session, method.lower()) # getattr() 函数用于返回一个对象属性值。
            url = self.set_url(urls) # set_url() 方法调用
            res = call(url, params=data) # 请求调用
            # 分析返回状态码和返回的异常
            # 直接被调用requests
            if res.status_code < 300:
                # OK, return http response
                return True, res.json() # 正常返回

            else:
                # The status is not equal 200 ,that server is error
                return False, res.json() # 其他状态下结果返回
        except Exception as e:
            logger.error(e) # 出现异常日志记录
            return False, e # 返回错误信息
获取sonar单个项目结果数据
    def get_sonar_list(self, sonar_name):
        """获取完整sonar结果列表信息"""
        try:
            s = SonarSession()
            # 调用和输出sonar测量指标数据字段
            status_code, component = s.func_call('/api/measures/component', 'get',
                                                 **{'additionalFields': 'metrics,periods',
                                                    'componentKey': '{}'.format(
                                                        sonar_name),
                                                    'metricKeys': 'alert_status,quality_gate_details,bugs,new_bugs,reliability_rating,new_reliability_rating,vulnerabilities,new_vulnerabilities,security_rating,new_security_rating,code_smells,new_code_smells,sqale_rating,new_maintainability_rating,sqale_index,new_technical_debt,coverage,new_coverage,new_lines_to_cover,tests,duplicated_lines_density,new_duplicated_lines_density,duplicated_blocks,ncloc,ncloc_language_distribution,projects,new_lines'})
            result = {}
            status_show, show = s.func_call('/api/components/show', 'get', **{'component': sonar_name})
            if status_code is False:
                return False, component
            if status_show is False:
                return False, component
            for m in component.get('component').get('measures'):
                result.update({m.get('metric'): m.get('value')})
            result.update({'analysisDate': show.get('component').get('analysisDate')})
            return True, result
        except Exception as e:
            return False, e
获取sonar用户结果
    def get_sonar_total_auth(self, sonar_name):
        """获取用户信息"""
        try:
            s = SonarSession()
            status_code, component = s.func_call('/api/permissions/users', 'get',
                                                 **{'projectKey': '{}'.format(sonar_name),'ps':500},)
            result = {}
            if status_code:
                result.update({'name':sonar_name, 'auth': component.get('users')})
            return True, result
        except Exception as e:
            return False, e

完整代码
# -*- coding: utf-8 -*-
import requests
from django.conf import settings
from urllib.parse import urljoin
import logging

logger = logging.getLogger(__name__)


class SonarSession(object):

    def __init__(self):
    	# 内置入口函数
        self.urls = settings.SONAR_URL
        self.token = settings.SONAR_TOKEN
        self.session = requests.Session()
        self.session.auth = self.token, ''

    def set_url(self, url):
    	# URL 拼接
        try:
            return urljoin(self.urls, url)
        except Exception as e:
            return None

    def func_call(self, urls, method, **data):
        # 封装调用函数
        # Get method and make the call
        try:
            call = getattr(self.session, method.lower())
            url = self.set_url(urls)
            res = call(url, params=data)
            # Analyse response status and return or raise exception
            # Note: redirects are followed automatically by requests
            if res.status_code < 300:
                # OK, return http response
                return True, res.json()

            else:
                # The status is not equal 200 ,that server is error
                return False, res.json()
        except Exception as e:
            logger.error(e)
            return False, e

    def get_sonar_detail(self, sonar_name):
        # 获取指定sonar结果
        try:
            s = SonarSession()
            status_code, component = s.func_call('/api/measures/component', 'get',
                                                 **{'additionalFields': 'metrics,periods',
                                                    'componentKey': '{}'.format(
                                                        sonar_name),
                                                    'metricKeys': 'bugs,vulnerabilities,blocker_violations,code_smells,lines,ncloc,comment_lines,files'})
            result = {}
            status_show, show = s.func_call('/api/components/show', 'get', **{'component': sonar_name})
            if status_code is False:
                return False, component
            if status_show is False:
                return False, component
            for m in component.get('component').get('measures'):
                result.update({m.get('metric'): m.get('value')})
            result.update({'analysisDate': show.get('component').get('analysisDate')})
            return True, result
        except Exception as e:
            return False, e
            
    def get_sonar_total_auth(self, sonar_name):
        # 获取用户信息
        try:
            s = SonarSession()
            status_code, component = s.func_call('/api/permissions/users', 'get',
                                                 **{'projectKey': '{}'.format(sonar_name),'ps':500},) #注意分页
            result = {}
            if status_code:
                result.update({'name':sonar_name, 'auth': component.get('users')})
            return True, result
        except Exception as e:
            return False, e

后续

# 更好的提意可以评论区。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

魔幻云

告诉自己是时候输出知识啦!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值