国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

利用jira及confluence的API進行批量操作(查找/更新/導出/備份/刪除等)

這篇具有很好參考價值的文章主要介紹了利用jira及confluence的API進行批量操作(查找/更新/導出/備份/刪除等)。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

前言:

近期因為某些原因需要批量替換掉 jira 和 confluence中的特定關鍵字,而且在替換前還希望進行備份(以便后續(xù)恢復)和導出(方便查看)
atlassian官方的api介紹文檔太簡陋,很多傳參都沒有進一步的描述說明,過程中踩了不少的坑...
故現將相關代碼分享下,希望有類似需求的朋友能用得上,直接上代碼:

?

from jira import JIRA
import requests
import re

'''
用途: jira單的查找、導出、更新、刪除等操作
author: tony
date: 2023
'''

class jira_tools():

    # jira API
    base_url = "http://your-jira-url.com/"
    username = "your_username"
    password = "your_password"
    jira = JIRA(base_url,basic_auth=(username, password))

    # 搜索關鍵字和替換關鍵字
    search_keyword = '查找關鍵詞'
    replace_keyword = '替換關鍵詞'

    def jira_search(self):
        '''查找標題和正文中包含特定關鍵字的issue
        返回一個list,list中的元素為jira issue對象<class 'jira.resources.Issue'>
        '''
        # 拼接jql,可按需修改(此處為搜索項目REQ和TREQ中的標題or描述中包含特定關鍵詞的issue)
        jql_query = 'project in (REQ,TREQ) AND (summary ~ "{0}" or description ~ "{0}") ORDER BY updated DESC'.format(self.search_keyword)
        # jql_query = 'summary ~ "{0}" or description ~ "{0}" ORDER BY updated DESC'.format(self.search_keyword)
        # jql_query = 'id = BUG-44257'
        
        # 每頁的大小(應該最大只支持50)
        page_size = 50

        # 初始化起始索引和總體issues列表
        start_at = 0
        all_issues = []

        while True:
            # 執(zhí)行查詢并獲取當前頁的問題
            issues = self.jira.search_issues(jql_query, startAt=start_at, maxResults=page_size)
            # 將當前頁的issues添加到總體issues列表
            all_issues.extend(issues)
            # 檢查是否已獲取所有issues
            if len(issues) < page_size:
                break
            # 更新起始索引以獲取下一頁
            start_at += page_size
        return all_issues

    def jira_export(self, issue_id, issue_summary):
        # 頁面上抓到的導出接口(需要先行在瀏覽器上登錄)
        export_url = 'http://your-jira-url.com/si/jira.issueviews:issue-word/{0}/{0}.doc'.format(issue_id)

        #替換掉標題中可能存在的特殊關鍵字,避免保存文件失敗
        issue_summary = re.sub(r'[【】|()()\\/::<>*]', '', issue_summary)
        filename = 'D:/jira_bak/{0}_{1}.doc'.format(issue_id, issue_summary)  # 下載后保存的文件名

        response = requests.get(export_url)

        if response.status_code == 200:
            try:
                with open(filename, 'wb') as f:
                    f.write(response.content)
                print('issue導出成功!')
            except Exception as e:
                print('issue導出失敗~失敗原因:{0}'.format(e))

    def jira_replace(self,issues):
        '''替換issue標題和正文中的特定關鍵字'''
        for issue in issues:
            issue_id = issue.key
            issue_obj = self.jira.issue(issue_id)
            # 獲取原始標題和描述
            old_summary = issue_obj.fields.summary
            old_description = issue_obj.fields.description
            # 先導出word
            self.jira_export(issue_id, old_summary)
            # 替換關鍵字
            new_summary = old_summary.replace(self.search_keyword, self.replace_keyword)
            # 更新問題的標題和描述(description)
            if old_description: # 描述可能為空
                new_description = old_description.replace(self.search_keyword, self.replace_keyword)
                issue_obj.update(summary=new_summary, description=new_description)
            else:
                issue_obj.update(summary=new_summary)
            # 更新問題的標題和描述
            print("{0}-{1} 關鍵詞替換成功".format(issue_id, old_summary))
    
    def jira_delete(self, issue_id):
        '''刪除特定的issue'''
        try:
            # 獲取issue
            issue = self.jira.issue(issue_id)
            # 刪除issue
            issue.delete()
            print("{0}刪除成功".format(issue_id))
        except Exception as e:
            print("{0}刪除失敗:{1}".format(issue_id, e))

# # 查找、備份/替換
# j = jira_tools()
# issues = j.jira_search()
# issues_id_list = [ issue.key for issue in issues]
# print(len(issues_id_list),issues_id_list)
# j.jira_replace(issues)

# 刪除
# j=jira_tools()
# j.jira_delete('TREQ-18431')

?

import requests
import re,os
import pandas as pd
from atlassian import Confluence  # pip install atlassian-python-api

'''
用途: confluence的查找、備份/導出、更新、刪除、恢復等相關操作
author: tony
date: 2023
'''

def save_content_to_file(filename, content, file_format='txt'):
    '''保存內容到文件'''
    if file_format=='pdf':
        directory = 'D:/wiki_bak/pdf/'
        filename = directory + filename + '.pdf'
    else:
        directory = 'D:/wiki_bak/txt/'
        filename = directory + filename + '.txt'
    try:
        os.makedirs(directory, exist_ok=True)
        with open(filename, 'wb' if file_format == 'pdf' else 'w', encoding='utf-8' if file_format != 'pdf' else None) as file:
            file.write(content)
        print("內容已保存到文件{0}".format(filename))
    except Exception as e:
        print("{0} 文檔保存時失敗:{1}".format(filename, e))

class wiki_tools():
    # Confluence API
    base_url = "http://your-confluence-url.com/"
    search_url = base_url + "/rest/api/search"
    content_url = base_url + "/rest/api/content"
    username = "your_username"
    password = "your_password"
    wiki_replace_record = 'D:/wiki_bak/wiki_replace_record.csv' #處理過的文檔概況

    # 搜索關鍵字和替換關鍵字
    search_keyword = '"查找關鍵詞"'  # 將搜索詞用""號擴起來表示進行整詞匹配,不會被confluence拆分成多個單詞進行匹配
    replace_keyword = '替換關鍵詞'


    def wiki_search(self):
        '''查找confluence文檔
        查找關鍵詞:
            search_keyword
        returns:
            list:匹配文檔的content_id(即URL上的pageId)
        '''
        content_id_list = []  # 用于記錄文檔id
        start = 0
        limit = 100
        total_size = 0

        while start <= total_size:
            # 構建搜索請求的URL
            search_url = "{0}?cql=type=page and (title~'{1}' OR text~'{2}')&start={3}&limit={4}".format(
                self.search_url, self.search_keyword, self.search_keyword, start, limit)
            # 發(fā)送搜索請求
            response = requests.get(search_url, auth=(self.username, self.password))
            search_results = response.json()
            total_size = search_results['totalSize']
            
            # 提取當前頁匹配的文檔 id
            page_content_id_list  = [ result['content']['id'] for result in search_results["results"]]
            content_id_list.extend(page_content_id_list)

            start += limit

        return content_id_list


    def wiki_replace(self,content_id):
        '''替換confluence文檔中的關鍵字'''
        # 獲取文檔正文部分內容
        # https://community.atlassian.com/t5/Confluence-questions/How-to-edit-the-page-content-using-rest-api/qaq-p/904345
        content_url = self.content_url + "/" + content_id + "?expand=body.storage,version,history"
 
        content_response = requests.get(content_url, auth=(self.username, self.password))

        if content_response.status_code == 200:
            content_data = content_response.json()

            # 獲取文檔最新的版本號
            latest_version = content_data["version"]["number"]

            # 獲取文檔的創(chuàng)建者
            createdBy = content_data["history"]["createdBy"]["displayName"]

            # 獲取文檔的創(chuàng)建時間 eg: 2023-05-30T11:02:44.000+08:00
            createdDate = content_data["history"]["createdDate"].split('T')[0]

            # 獲取文檔的標題
            old_title = content_data["title"]
            # 替換掉標題中的特殊字符,避免無法作為文件命名
            old_title = re.sub(r'[【】|()()\\/::<>*]', '', old_title)

            # 獲取文檔的正文
            old_body = content_data["body"]["storage"]["value"]

            # 保存文檔標題和正文內容(文件名稱: contentid_title, 文件內容: body),以便后續(xù)恢復
            save_content_to_file(content_id + "_" + old_title, old_body)

            # 記錄所有處理過的文檔概要信息到csv文件(mode='a'即追加模式寫入)
            pd.DataFrame(data=[[content_id, old_title, createdBy, createdDate]]).to_csv(self.wiki_replace_record, encoding='utf-8', index=None, mode='a', header=None)

            # 導出文檔內容為pdf(方便直接查看)
            try:
                self.wiki_export_pdf(content_id, old_title + '_' + createdBy + '_' + createdDate)
            except Exception as e:
                # 有些文檔較大可能會超時
                print("{0}文檔導出時發(fā)生異常:{1}".format(content_id, e))

            # 避免出現無效更新造成version無謂增加
            if self.search_keyword in old_title or self.search_keyword in old_body:
                # 替換文檔標題和正文中的關鍵字
                new_title = old_title.replace(self.search_keyword, self.replace_keyword)
                new_body = old_body.replace(self.search_keyword, self.replace_keyword)
        
                # 更新文檔
                update_data = {
                    "title": new_title,
                    "type": content_data["type"],
                    "version":{
                        "number": latest_version + 1  # 使用最新版本號加1
                    },
                    "body": {
                        "storage": {
                            "value": new_body,
                            "representation": "storage"
                        }
                    }
                }
                update_response = requests.put(content_url, auth=(self.username, self.password), json=update_data)

                if update_response.status_code == 200:
                    print("替換成功:", old_title)
                else:
                    print("替換失?。?, old_title)
            else:
                print("文檔中未包含關鍵字:{0},無需更新".format(self.search_keyword))


    def wiki_update_from_file(self, content_id, title, body):
        '''指定內容更新'''
        content_url = self.content_url + "/" + content_id + "?expand=body.storage,version"
        content_response = requests.get(content_url, auth=(self.username, self.password))

        if content_response.status_code == 200:
            content_data = content_response.json()

            # 獲取文檔最新的版本號
            latest_version = content_data["version"]["number"]

            # 更新文檔
            update_data = {
                "title": title,
                "type": content_data["type"],
                "version":{
                    "number": latest_version + 1  # 使用最新版本號加1
                },
                "body": {
                    "storage": {
                        "value": body,
                        "representation": "storage"
                    }
                }
            }
            update_response = requests.put(content_url, auth=(self.username, self.password), json=update_data)
            
            if update_response.status_code == 200:
                print("恢復成功:", title)
            else:
                print("恢復失敗:", title)


    def wiki_restore(self, path="D:/wiki_bak/txt/"):
        '''根據備份的body文件恢復對應的confluence文檔'''
        # 獲取指定路徑下的所有文件
        files = os.listdir(path)
        for file_name in files:
            # 根據文件名解析content_id、標題 ( 形如: contentid_title.txt )
            content_id = file_name.split('_')[0]
            title = file_name.split('_')[1].replace('.txt','')
            file_path = os.path.join(path, file_name)
            # 讀取備份文件并恢復
            if os.path.isfile(file_path):
                print('開始處理',file_path)
                with open(file_path, 'r') as file:
                    content = file.read()
                    self.wiki_update_from_file(content_id, title, content)


    def wiki_export_pdf(self, content_id, filename):
        '''利用atlassian-python-api庫導出pdf'''
        confluence = Confluence(
            url=self.base_url,
            username=self.username,
            password=self.password)
        page = confluence.get_page_by_id(page_id=content_id)
        response = confluence.get_page_as_pdf(page['id'])
        save_content_to_file(filename, content=response, file_format='pdf')


    def wiki_delete(self,content_id):
        '''利用atlassian-python-api庫刪除特定文檔'''
        confluence = Confluence(
            url=self.base_url,
            username=self.username,
            password=self.password)
        try:
            confluence.remove_content(content_id)
            print("文檔 {0} 刪除成功".format(content_id))
        except Exception as e:
            print("文檔 {0} 刪除失敗: {1}".format(content_id, e))


# w = wiki_tools()
# # 批量查詢&替換wiki文檔,同時備份替換前的內容
# contentid_list = w.wiki_search()
# print(contentid_list)
# for i in contentid_list:
#     print("----開始處理:{0}----".format(i))
#     w.wiki_replace(i)

# # 根據備份的文件恢復wiki文檔內容
# w.wiki_restore()

# # 刪除特定的文檔 
# w.wiki_delete('137295690')

?文章來源地址http://www.zghlxwxcb.cn/news/detail-468677.html

到了這里,關于利用jira及confluence的API進行批量操作(查找/更新/導出/備份/刪除等)的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。如若轉載,請注明出處: 如若內容造成侵權/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經查實,立即刪除!

領支付寶紅包贊助服務器費用

相關文章

  • 基于mybatis進行批量更新

    MyBatis是一種基于Java的持久層框架,提供了一種優(yōu)雅的方式來進行數據庫操作。對于批量更新數據操作,MyBatis 提供了兩種方法:使用 foreach 標簽和 batch 執(zhí)行器。 使用 foreach 標簽 使用 foreach 標簽時,需要編寫 SQL 語句,使用 ${} 或 #{} 占位符傳遞參數。示例: id:SQL 語句的標

    2024年02月17日
    瀏覽(17)
  • C++中利用OpenCV進行圖像批量處理

    C++中利用OpenCV進行圖像批量處理

    想要對大量圖像進行簡單處理,我們可以利用代碼實現。 OpenCV作為開源的圖像處理庫,安裝方便,容易上手,功能強大,受到了很多人的喜愛。 筆者正在參加全國大學生智能汽車競賽。由于放假在家,家中沒有鋪設賽道的條件,我找到了一款上位機,可以將智能車的圖像導

    2024年02月03日
    瀏覽(21)
  • Elasticsearch Java API 的使用-更新索引(update & upset)與 Bulk的批量更新

    Java更新索引(update upset) update 更新使用UpdateRequest(update類型更新,只能更新) upset 要用IndexRequest設定添加文檔,UpdateRequest設定更新文檔,設定upset執(zhí)行有則修改無則更新(upset類型更新,文檔不存在時創(chuàng)建) 基于Bulk的批量更新(update upset) 動態(tài)的更新一個 documents 中的任

    2024年02月11日
    瀏覽(27)
  • 利用Sqlmap API接口聯動Google Hacking批量SQL注入檢測

    利用Sqlmap API接口聯動Google Hacking批量SQL注入檢測

    目錄 前言 slghack自動化搜集URL Sqlmap API 腳本slghack_sqli 挖掘SQL注入漏洞的一種方式就是通過Google Hacking搜索那些可能存在SQL的URL,然后手工的探測注入點。但是現在的SQL注入漏洞的網站是比較少的了,所以這樣一個一個手工測效率有一點低。 sqlmap比較好的一點是可批量掃描多個

    2024年04月14日
    瀏覽(26)
  • 利用ChatGPT如何進行批量長文本處理工具GPTBAT

    大家好,我是技術宅小伙,今天要跟大家分享一下我之前寫的 GPT 長文本處理程序。當時我寫完后就把它放到 Hog 上了,因為最開始是為了自己用,所以后來就忘掉了。最近有同學把它翻出來用,然后經常來問我,說不知道這個東西怎么用。其實在我看來這個挺簡單的,但是如

    2023年04月22日
    瀏覽(22)
  • 數據批量操作:如何在HBase中進行批量操作

    HBase是一個分布式、可擴展、高性能的列式存儲系統,基于Google的Bigtable設計。它是Hadoop生態(tài)系統的一部分,可以與HDFS、MapReduce、ZooKeeper等其他組件集成。HBase適用于大規(guī)模數據存儲和實時數據訪問場景,如日志記錄、實時數據分析、實時數據流處理等。 在HBase中,數據以列族

    2024年04月23日
    瀏覽(26)
  • Java API批量操作Elasticsearch

    Java API批量操作Elasticsearch

    @Test public void batchAddIndex() throws IOException { BulkRequestBuilder bulkRequest = client .prepareBulk(); bulkRequest.add( client .prepareIndex( “batch_test1” , “batch” , “1” ) .setSource( jsonBuilder () .startObject() .field( “user” , “l(fā)zq” ) .field( “postDate” , new Date()) .field( “message” , “trying out Elasticsearch”

    2024年04月09日
    瀏覽(26)
  • HBase Java API 開發(fā):批量操作 第2關:批量刪除數據

    刪除單行數據 刪除一行數據很簡單,我們來看個示例: 這段代碼就可以刪除行鍵為 row1 的行。 刪除多行數據 如何刪除多行數據呢? 相信你已經猜到了,既然 get() 方法有重載方法,那應該 delete() 方法也有,確實: 這樣就可以刪除多行數據啦。 編程要求 還等啥,親自試一試

    2024年02月05日
    瀏覽(137)
  • 數據庫高效批量更新操作 MERGE INTO

    使用 UPDATE 批量更新大量的數據,會出現效率低下,有時候甚至卡死的情況,后面通過使用 MERGE INTO 代替 UPDATE 執(zhí)行批量更新,會提升執(zhí)行效率。 原理:因為 UPDATE 關聯子查詢寫法,是選到一條做一次子查詢,這種寫法得更新少,走好的索引才行,MERGE 寫法是執(zhí)行完 ON 后一次

    2024年02月17日
    瀏覽(13)
  • 對分庫分表進行批量操作

    對分庫分表進行批量操作

    對ShardingJDBC基礎了解:https://blog.csdn.net/m0_63297646/article/details/131894472 對批量操作案例:https://blog.csdn.net/m0_63297646/article/details/131843517 分為db0和db1兩個庫,每個庫都有三張訂單表,分表鍵根據年份【year】,分庫鍵根據店鋪id【store_id】 在db0中存在兩張學生信息表,分表鍵根據年

    2024年02月10日
    瀏覽(18)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領取紅包,優(yōu)惠每天領

二維碼1

領取紅包

二維碼2

領紅包