Python create Confluence Page

Python script to create a Confluence page, plus child pages, based on input .txt files in Confluence markup language. In my case called from Jenkins with a Jenkins parameter (p_test_description) used to name the Confluence page.

#!/usr/bin/python
###################################################################################
# Name : awrConfluence.py
# Purpose : Create confluence page (+ child pages) of database analysis
#     Based on https://stackoverflow.com/questions/33168060/how-can-i-create-a-new-page-to-confluence-with-python
# Parameters : 1 = p_test_description free text description field in jenkins job
# Change History :
###################################################################################
# initialize
import requests
import json
import argparse
import datetime
import sys
from requests.auth import HTTPBasicAuth
# Global variables: set auth token and get the basic auth code
auth_token = 'nftauto'
basic_auth = HTTPBasicAuth('myConfluenceUser', auth_token)
space_key = 'myConfluenceSpace'
url = 'https://myConfluenceServer.myDomain.com/rest/api/content/'
parser = argparse.ArgumentParser()
parser.add_argument('p_test_description')
args = parser.parse_args()
###################################################################################
def pageExists(page_title):   # checks if confluence page already exists
    # Request Headers
    headers = {
        'Content-Type': 'application/json;charset=iso-8859-1',
    }
    # Request body
    data = {
        'type': 'page',
        'title': page_title,
        'space': {'key':space_key}
    }
    try:
        r = requests.get(url=url, params=data, headers=headers, auth=basic_auth)
        # Consider any status other than 2xx an error
        if not r.status_code // 100 == 2:
            print("Error: Unexpected response {}".format(r))
            sys.exit()
        else:
            if 'id' in r.text and r.json()['results'][0]['id'].isdigit():
                return True
            else:
                return False
    except requests.exceptions.RequestException as e:
        # A serious problem happened, like an SSLError or InvalidURL
        print("Error: {}".format(e))
        sys.exit()
###################################################################################
def createPage(page_title, parent_page_id, inputTextFile):   # creates a confluence page, returns the new page ID.
    # Set the title and content of the page to create. Utf8 encoding is needed to deal with 201a low-9 quotation mark symbol in activity charts.
    with open(inputTextFile, 'r', encoding='utf8') as text_file:
        page_html = text_file.read()
    # Request Headers
    headers = {
        'Content-Type': 'application/json;charset=iso-8859-1',
    }
    # Request body
    data = {
        'type': 'page',
        'title': page_title,
        'ancestors': [{'id':parent_page_id}],
        'space': {'key':space_key},
        'body': {
            'storage':{
            'value': page_html,
                'representation':'wiki',
            }
        }
    }
    try:
        r = requests.post(url=url, data=json.dumps(data), headers=headers, auth=basic_auth)
        # Consider any status other than 2xx an error
        if not r.status_code // 100 == 2:
            print("Error: Unexpected response {}".format(r))
            print(r.text)
            return('Error')
        else:
            return r.json()['id']
    except requests.exceptions.RequestException as e:
        # A serious problem happened, like an SSLError or InvalidURL
        print("Error: {}".format(e))
        return('Error')
###################################################################################
# main block
page_name = " ".join(args.p_test_description.split())  # strip out extra space characters (if any)
if page_name == '':
    page_name = '{:%Y%m%d%H%M%S}'.format(datetime.datetime.now())
elif pageExists("DB Analysis " + page_name) or pageExists("Load Comparison " + page_name) or pageExists("All SQL Comparison " + page_name) or pageExists("Sql Analysis " + page_name) or pageExists("Database Activity " + page_name) or pageExists("Delete " + page_name):
    page_name = page_name + ' {:%Y%m%d%H%M%S}'.format(datetime.datetime.now())
page_id = createPage("DB Analysis " + page_name, 66666666, 'dbAnalysis.txt')  # replace 66666666 with the confluence page number of your desired overall parent page.
if page_id != 'Error':
    child_page_id = createPage("Database Activity " + page_name, page_id, 'databaseActivity.txt')
    child_page_id = createPage("Load Comparison " + page_name, page_id, 'load_comp.txt')
    child_page_id = createPage("Sql Analysis " + page_name, page_id, 'sql_comp.txt')
    child_page_id = createPage("All SQL Comparison " + page_name, page_id, 'all_sql_comp.txt')
    child_page_id = createPage("Additional Info " + page_name, page_id, 'chart.txt')
    print(f"Confluence page created as https://myConfluenceServer.myDomain.com/display/nonfuntst/DB+Analysis+{page_name.replace(' ', '+')} ")
###################################################################################

Based on https://stackoverflow.com/questions/33168060/how-can-i-create-a-new-page-to-confluence-with-python

May 29, 2023

Leave a Reply

Your email address will not be published. Required fields are marked *