def get_page_url(page_title: str, space: str, confluence: Confluence) -> Union[str, None]: """Retrieves page URL""" if page := confluence.get_page_by_title(space=space, title=page_title, expand=""): # according to Atlassian REST API reference, '_links' is a legitimate way to access links page_link = confluence.url + page["_links"]["webui"] return page_link
def get_content_id_by_title(con: Confluence, title: str, space_key: str, test_run: bool): if not space_key: raise BadParamsException('You have to add space_key if you specify ' 'parent by title!') p = con.get_page_by_title(space_key, title) if p and 'id' in p: return p['id'] elif test_run: return None else: raise BadParamsException(f'Cannot find parent with title {title}')
class ConfluenceHelper: def __init__(self, url, username, password, space): self.confluence = Confluence(url=url, username=username, password=password) self.space = space def create_page(self, title, body, parent_title): # Do some crazy page creation result = self.confluence.get_page_by_title(space=self.space, title=parent_title) parent_id = result["id"] result = self.confluence.create_page(space=self.space, title=title, body=body, parent_id=parent_id) page = result return True, page
# coding: utf8 from atlassian import Confluence confluence = Confluence( url='http://localhost:8090', username='******', password='******') # If you know Space and Title content1 = confluence.get_page_by_title(space='SPACE', title='page title') print(content1) # If you know page_id of the page content2 = confluence.get_page_by_id(page_id=1123123123) print(content2)
class ConfluenceAdapter(object): """ Adapter for Atlassian Confluence class. Encapsulates content retrieve and update functionality. """ NAMESPACES = { "atlassian-content": "http://atlassian.com/content", "ac": "http://atlassian.com/content", "ri": "http://atlassian.com/content", "atlassian-template": "http://atlassian.com/template", "at": "http://atlassian.com/template", } def __init__(self, url, username, password, space_key): self.confluence = Confluence(url=url, username=username, password=password) self.space_key = space_key self.get_space_or_create() def get_space_or_create(self): """ Check whether space exists or not. If it doesn't, then create the space. :rtype: dict :return: Space data. """ space = self.confluence.get_space(self.space_key) if type(space) is not dict: raise WikiUpdateException("Can't retrieve valid information about Confluence space." " Please check configurations. Data: {}".format(space)) if space.get('statusCode', None) == 404: space = self.confluence.create_space(self.space_key, self.space_key) return space def get_page_or_create(self, page_title): """ Get page content, if no such page then create it. :type page_title: str :param page_title: Title of the page which should be retrieved. :raises: WikiUpdateException :rtype: tuple(int, lxml.etree._Element) :returns: Tuple where first element is the id of the page. The second is the parsed content data. """ data = self.confluence.get_page_by_title(title=page_title, space=self.space_key, expand="body.storage,version") if not data: # No such page exist. Then create such page. data = self.create_page(page_title) try: content_xml = data['body']['storage']['value'] except KeyError: raise WikiUpdateException("Can't get partial-devices page content.") body_xml = render_to_string('wrapper.xml', { 'content': content_xml }) return data['id'], etree.fromstring(body_xml) def create_page(self, page_title): """ Create new page.+ :type page_title: str :param page_title: Title of the page which should be created. :raises: WikiUpdateException :rtype: dict :return: Data of newly created page. """ data = self.confluence.create_page(self.space_key, page_title, body="") if not data or 'id' not in data: raise WikiUpdateException("Page `{}` could not be created. Response data: {}".format(page_title, data)) return data def update_page_content(self, page_id, page_title, body): """ Update existing page with new body. :type page_id: int :param page_id: Page id which should be modified. :type page_title: str :param page_title: Title of the page which should be modified. :type body: lxml.etree._Element :param body: Page content data. :raises: WikiUpdateException :rtype: dict :returns: Data of newly updated page. """ # Get raw xml. body_xml = etree.tostring(body).decode('utf-8') # <xml xmlns:******> <p></p>***<ac:structured-macro>***</ac:structured-macro> </xml> # ^ ^ # Take the content starting right after `>` of the opening xml tag and till `<` of xml closing tag. content_xml = body_xml[body_xml.find('>') + 1:body_xml.rfind('<')] data = self.confluence.update_existing_page(page_id, page_title, content_xml) if not data or 'id' not in data: raise WikiUpdateException("Page `{}` could not be updated. Response data: {}".format(page_title, data)) return data @classmethod def get_field_element(cls, element, field): """ Get element from tree by field name. :rtype: lxml.etree._Element :returns: Element data. """ return element.xpath('//ac:structured-macro/ac:parameter' '[@ac:name="MultiExcerptName" and translate(normalize-space(text()), " ", "")="{}"]' '/following-sibling::ac:rich-text-body/*[local-name()="p"]'.format(field.name), namespaces=cls.NAMESPACES) @classmethod def update_content_for_field(cls, page_content, field): """ Update content for field. :type page_content: lxml.etree._Element :param page_content: Wiki page content. :type field: AbstractLinkedField :param field: Field for which the page_content should be updated. :rtype: lxml.etree._Element :returns: Page content data. """ field_elements = cls.get_field_element(page_content, field) if not field_elements: # If element does not exist then create it. macro_id = uuid.uuid4() data = render_to_string('multiexcerpt.xml', { "macro_id": macro_id, "field_name": field.name, "field_value": field.provide_value() }) element = etree.fromstring(data) page_content.insert(-1, element) # Can leave without this return, but `Explicit is better than implicit.` (C) Python Zen. return page_content for field_element in field_elements: field_element.text = field.provide_value() return page_content
<p class="auto-cursor-target"><br /></p></ac:rich-text-body></ac:structured-macro>\ <p style="text-align: center;">★ : 완료, <span style="color: rgb(51,102,255);">★</span> : 진행중, \ <span style="color: rgb(255,0,0);">★</span> : 지연</p>\ <h3><span style="color: rgb(0,0,255);">● 프로젝트 리소스</span></h3>\ <table><colgroup><col style="width: 15%;" /><col style="width: 75%;" /><col style="width: 10%;" /></colgroup><tbody>\ <tr><th colspan="1" style="text-align: center;">PL</th><th style="text-align: center;">투입인원(' + \ str(table_project.loc[data_index[0]]['member']) + '명)</th><th style="text-align: center;">누적 리소스(hours)</th></tr>\ <tr><td colspan="1" style="text-align: center;">' + table_project.loc[data_index[0]]['projectLead'] + '</td><td><span>' + table_project.loc[data_index[0]]['member_List'] + '</span></td><td style="text-align: center;"><span>' + str(table_project.loc[data_index[0]]['totalTime']) + '</span></td></tr></tbody></table>\ <p class="auto-cursor-target"><br /></p>\ <h3><span style="color: rgb(0,0,255);"><strong>● </strong>프로젝트 주요이슈/특이사항</span></h3>\ <table><colgroup><col /><col /><col /><col /><col /><col /><col />\ </colgroup><tbody><tr><th style="text-align: center;">Milestone</th><th style="text-align: center;">종료일\ </th><th style="text-align: center;" colspan="1">상태</th><th style="text-align: center;">미해결 이슈</th>\ <th style="text-align: center;">전체 이슈</th><th style="text-align: center;" colspan="1">지연 이슈</th>\ <th style="text-align: center;">주간 보고 특이사항</th></tr>' + tableRow2 + '</tbody></table><p><br /></p>' # Wiki 페이지 생성 confluence.create_page( space='RNDPRO006', title= table_version.loc[data_index[0]]['projectName'] + ' (' + nowdate + ')', body='{0}'.format(wiki_data), parent_id=93392437, type='page' ) page_id = confluence.get_page_by_title('RNDPRO006', table_version.loc[data_index[0]]['projectName'] + ' (' + nowdate + ')', start=None, limit=None) data = [{"prefix":"global","name":"프로젝트주간보고"}] headers = {'Content-Type': 'application/json'} requests.post('https://wiki.telechips.com:8443/rest/api/content/' + page_id['id'] + '/label', data=json.dumps(data), headers=headers, auth=(username, password))
from pprint import pprint from atlassian import Confluence confluence = Confluence( url='http://localhost:8090', username='******', password='******') # If you know Space and Title content1 = confluence.get_page_by_title( space='SPACE' title='page title') pprint(content1) # If you know page_id of the page content2 = confluence.get_page_by_id(page_id=1123123123) pprint(content2)
# coding=utf-8 from atlassian import Confluence confluence = Confluence(url="http://localhost:8090", username="******", password="******") # If you know Space and Title content1 = confluence.get_page_by_title(space="SPACE", title="page title") print(content1) # If you know page_id of the page content2 = confluence.get_page_by_id(page_id=1123123123) print(content2)