Jira-API的详细使用例子

Jira-API的详细使用例子

下面是Jira-API的详细使用的例子,包含:

  • Jira的登陆,通过jql批量查询jira-issue,
  • 获得jira-project下的所有issue,assignee的详细信息,
  • 添加和更新defect
  • 下载和上传附件
  • 通过Jira登录的cookies搭配requsts库发送自定义的一些http请求
 
# -*- coding: UTF-8 -*-
import traceback
import requests
from atlassian import Jira
from jira import JIRA
import globalParam
jira = object
jira2 = object
#url是jira的地址
url = "https://www.Jira.com"
# 登录jira,成功为1,失败为0
def login(username, password):
    global jira, jira2
    result = 2
    try:
        jira = JIRA(server=url, basic_auth=(username, password), max_retries=1, timeout=400)
        jira2 = Jira(url=url, username=username, password=password)
        globalParam.reporter = get_current_user()
    except Exception:
        result = 0
        return result
    result = 1
    return result
# 获得一个项目的所有assignee的信息
def get_all_assignable_users_by_project_key(project_key):
    return jira2.get_all_assignable_users_for_project(project_key)
#下载附件到本地
def download_attachment(jira_attachment_id, filepath):
    attachment = jira.attachment(jira_attachment_id)
    image = attachment.get()
    with open(filepath, 'wb') as f:
        f.write(image)
#删除Jira上的附件
def delete_attachment(jira_attachment_id):
    jira.delete_attachment(jira_attachment_id)
#获得当前登陆的用户名
def get_current_user():
    return jira.myself()['displayName']
#获得当前登陆的用户的Key
def get_current_eid():
    return jira.myself()['key']
#根据jira-key获得开发人员
# key 可以是key'JIRA-1451'
def get_assignee(self, key):
    global jira
    issue = jira.issue(key)
    return issue.fields.assignee
#获得所有的Jira项目
def get_all_project():
    try:
        projects = jira.projects()
    except Exception:
        print(traceback.format_exc())
        result = 0
        return result
    return projects
# 根据jira-project-key参数获得所有的issue的各类信息
def get_issues_by_project_key(project_key):
    # 因为component从jira取出来是list,所以用逗号将它分割,重新组合成string
    jqlstring = "project = " + project_key + " AND issuetype = Defect ORDER BY updated DESC"
    try:
        query = jira.search_issues(
            jql_str=jqlstring,
            json_result=True,
            fields="key,summary,description,environment,comment,"
                   "components,labels,assignee,reporter,status,attachment,updated",
            maxResults=4000)
    except Exception:
        print(traceback.format_exc())
        result = 0
        return result
    issues = query["issues"]
    return issues
# 根据jira-project-key参数和时间获得所有的issue的各类信息
def get_issues_by_project_key_and_time(project_key, last_synctime):
    # 因为component从jira取出来是list,所以用逗号将它分割,重新组合成string
    jqlstring = "project = " + project_key + " AND updatedDate >='" + last_synctime + 
                "' AND issuetype = Defect ORDER BY updated DESC"
    try:
        query = jira.search_issues(
            jql_str=jqlstring,
            json_result=True,
            fields="key,summary,description,environment,comment,"
                   "components,labels,assignee,reporter,status,attachment,updated",
            maxResults=4000)
    except Exception:
        print(traceback.format_exc())
        result = 0
        return result
    issues = query["issues"]
    return issues
#根据jira-project-key参数获得所有的component信息
def get_components_by_project_key(project_key):
    try:
        components = jira.project_components(project_key)
    except Exception:
        print(traceback.format_exc())
        result = 0
        return result
    return components
#根据jira-project-key参数获得所有的version信息
def get_version_by_project_key(project_key):
    jira_project = jira.project(project_key)
    versions = jira_project.versions
    return versions
#添加一个defect
def add_defect(project_key, summary, description, steps_to_reproduce, labels, defect_severity, env, components,
               frequency, product_id, version_name, assignee_eid):
    jira_project = jira.project(project_key)
    label_list = labels.split(",")
    pid = jira_project.id
    if isinstance(product_id, int):
        product_id = str(product_id)
    components_list = []
    components_name = components.split(",")
    for item in components_name:
        components_list.append({"name": item})
    issue_dict = {
        'project': {'id': pid},
        'summary': summary,
        'description': description,
        'issuetype': {'name': 'Defect'},
        'labels': label_list,
        'customfield_10040': {"value": defect_severity},  # BUG的Defect Severity字段
        'customfield_10033': steps_to_reproduce,  # BUG的描述步骤
        'environment': env,
        'components': components_list,
        'customfield_10336': {"value": frequency},
        'customfield_13600': product_id,
        'customfield_11170': {"name": version_name},
        "assignee": {"name": assignee_eid}
    }
    if assignee_eid is None:
        del issue_dict['assignee']
    if env == "":
        del issue_dict['environment']
    if components == "":
        del issue_dict['components']
    if product_id == "" or product_id == "n":
        del issue_dict['customfield_13600']
    if version_name == "":
        del issue_dict['customfield_11170']
    new_issue = jira.create_issue(fields=issue_dict)
    return new_issue.key
#更新一个defect
def update_defect(issue_key, summary, description, steps_to_reproduce,
                  labels, defect_severity, env, components, frequency, product_id, version_name, assignee_eid):
    issue = jira.issue(issue_key)
    label_list = labels.split(",")
    components_list = []
    components_name = components.split(",")
    if components == "":
        pass
    for item in components_name:
        components_list.append({"name": item})
    issue_dict = {
        'summary': summary,
        'description': description,
        'issuetype': {'name': 'Defect'},
        'labels': label_list,
        'customfield_10040': {"value": defect_severity},  # BUG的Defect Severity字段
        'customfield_10033': steps_to_reproduce,  # BUG的描述步骤
        'environment': env,
        'components': components_list,
        'customfield_10336': {"value": frequency},
        'customfield_13600': str(product_id),
        'customfield_11170': {"name": version_name},
        "assignee": {"name": assignee_eid}
    }
    if assignee_eid is None:
        del issue_dict['assignee']
    if env == "":
        del issue_dict['environment']
    if components == "":
        del issue_dict['components']
    if version_name == "":
        del issue_dict['customfield_11170']
    update_issue = issue.update(fields=issue_dict)
    cccc = update_issue
    return issue_key
#将一个本地的附件上传到Jira上
def add_attachment(issue, path, filename):
    newpath = path.encode('utf-8')
    cc = unicode(newpath, "utf-8")
    result = jira.add_attachment(issue=issue, attachment=cc, filename=filename)
    return result
#根据jira-key获得该issue所有的附件
def get_attachment(issue_key):
    issue = jira.issue(issue_key)
    return issue.fields.attachment
#通过项目project_key值,抓取页面上的一些自定义参数,例如自定义参数13600,对应products参数
def get_products_by_project_key(project_key):
    product_map = {}
    jiraproject = jira.project(project_key)
    #jira._session.cookies可以用来搭配requests库,发送请求
    cookies = jira._session.cookies
    body = {"pid": jiraproject.id}
    url = "https://www.jira.com/secure/QuickCreateIssue!default.jspa?decorator=none"
    result = requests.post(url, data=body, cookies=cookies,
                           headers={"Content-type": "application/x-www-form-urlencoded"})
    html = result.text
    try:
        select1 = html.split('"id":"customfield_13600","label":"Product/s","required":false,')[1]
        select2 = select1.split('</select>')[0]
        if not select2.__contains__("\n\tNone\n\n"):
            select3 = select2.split('<option')
            c = select3
            for item in select3:
                if item.__contains__('value='):
                    patern_id = item.split('value=\"')[1]
                    id = patern_id.split('\"')[0]
                    patern_value = item.split("\n    ")
                    value = patern_value[1].strip()
                    product_map[id] = value
    except Exception:
        # print(traceback.format_exc())
        pass
    return product_map
#给一个jira-issue添加comment
def add_comment(issue_key, comment_body):
    comment = jira.add_comment(issue_key, comment_body)
    return comment.id

苏ICP备18047533号-1