# coding: utf8
from atlassian import Confluence

confluence = Confluence(
    url='http://localhost:8090',
    username='******',
    password='******')
# this example related get all user from group e.g. group_name
group_name = 'confluence-users'
flag = True
i = 0
limit = 50
result = []
while flag:
    response = confluence.get_group_members(group_name=group_name, start=i * limit, limit=limit)
    if response and len(response):
        i += 1
        result.append(response)
    else:
        flag = False
print(result)
def setup_confluence(use_oauth=False):
    """setup_confluence Set up the Confluence class instance

    Reads in the confluence.conf configuration file, which contains the URL,
    username, and password (and/or OAUTH info).

    NOTE: For Confluence install version >= 7.9, can use OAUTH for
          authentication instead of username/password.

    Parameters
    ----------
    use_oauth : `bool`, optional
        Use the OAUTH authentication scheme?  [Default: False]

    Returns
    -------
    confluence : `atlassian.Confluence`
        Confluence class, initialized with credentials
    """
    # Read the setup
    setup = utils.read_ligmos_conffiles("confluenceSetup")

    # If we are using OAUTH, instantiate a Confluence object with it
    if use_oauth:
        s = requests.Session()
        s.headers["Authorization"] = f"Bearer {setup.access_token}"
        return Confluence(url=setup.host, session=s)

    # Else, return a Confluence object instantiated with username/password
    return Confluence(url=setup.host,
                      username=setup.user,
                      password=setup.password)
Beispiel #3
0
def update_html_content(login, passw, html):
    c = Confluence(BASE_URL, login, passw)
    page = c.get_page_by_id(page_id=JENKINS_PAGE_ID, expand='body.storage')
    resp = c.update_existing_page(page_id=JENKINS_PAGE_ID,
                                  body=html,
                                  title=page['title'])
    return resp.ok
Beispiel #4
0
    def __init__(
        self,
        url,
        username,
        apiToken,
        pageTitlePrefix,
        markdownDir,
        dbPath,
        space,
        parentPageId,
        forceUpdate=False,
        forceDelete=False,
        skipUpdate=False,
    ):
        self.api = Confluence(url=url, username=username, password=apiToken)
        self.pageTitlePrefix = pageTitlePrefix
        self.markdownDir = markdownDir
        self.kv = KeyValue(dbPath)
        self.space = space
        self.parentPageId = parentPageId
        self.forceUpdate = forceUpdate
        self.forceDelete = forceDelete
        self.skipUpdate = skipUpdate
        self.confluenceRenderer = ConfluenceRenderer(url)
        self.metadataPlugin = MetadataPlugin()
        self.renderer = mistune.create_markdown(
            renderer=self.confluenceRenderer,
            plugins=[
                'strikethrough', 'footnotes', 'table', 'url',
                self.metadataPlugin.plugin_metadata
            ])

        # Hack to allow metadata plugin to work (See mistune/block_parser.py)
        self.renderer.block.rules.remove('thematic_break')
def atl_login(request, body, *args, **kwargs):
    """
    Update atlassian login info
    Method: Post
    Request: first_name,last_name,old_password,password
    """
    try:
        user = request.session.get('user', {})
        # if user['atl_login']:
        #     resp = init_http_response_my_enum(RespCode.success)
        #     return make_json_response(resp=resp)

        user['atl_username'] = body['atl_username']
        user['atl_password'] = body['atl_password']
        # user['atl_login'] = True
        request.session['user'] = user

        confluence = Confluence(
            url='https://confluence.cis.unimelb.edu.au:8443/',
            username=request.session['user']['atl_username'],
            password=request.session['user']['atl_password'])

        conf_resp = confluence.get_all_groups()

        # print("~~")
        # print(request.session['user']['atl_username'])
        resp = init_http_response_my_enum(RespCode.success)
        return make_json_response(resp=resp)
    except requests.exceptions.HTTPError as e:
        resp = init_http_response_my_enum(RespCode.server_error)
        return make_json_response(resp=resp)
Beispiel #6
0
class ConfluenceManager:
    def __init__(self, credentials, path):
        self.remote = Confluence(url=credentials[0],
                                 username=credentials[1],
                                 password=credentials[2])

        def converter_to_local_key(key):
            if isinstance(key, tuple):
                return 'name_' + key[0] + key[1]
            else:
                return 'id_' + key

        self.cached = CachedDataProvider(
            self, path, converter_to_local_key=converter_to_local_key)
        self.simplified = CachedDataProvider(
            ConfluenceSimplifiedTextProvider(self.cached),
            path + '.simplified',
            converter_to_local_key=converter_to_local_key)

    def extract_url(self, raw_page):
        return self.remote.url + raw_page['_links']['webui']

    def extract_title(self, raw_page):
        return raw_page['title']

    def __get_page_id(self, id_):
        if isinstance(id_, tuple):
            id_ = self.remote.get_page_id(id_[0], id_[1])
        return id_

    def get_page(self, id_, full_info=True):
        id_ = self.__get_page_id(id_)

        expand = 'children.page.id'
        if full_info:
            expand = 'version,body.storage,children.page.id'

        raw = self.remote.get_page_by_id(id_, expand=expand)
        return raw

    def get_simple_text(self, id_):
        return self.simplified[id_]

    def get_page_tree_ids(self, id_):
        page = self.get_page(id_, full_info=False)
        ret = [page['id']]
        children_ids = [r['id'] for r in page['children']['page']['results']]
        for id_ in children_ids:
            ret += self.get_page_tree_ids(id_)
        return ret

    def __getitem__(self, key):
        if isinstance(key, tuple):
            remote_key = self.remote.get_page_id(key[0], key[1])
        else:
            remote_key = key

        ret = self.remote.get_page_by_id(
            remote_key, expand='version,body.storage,children.page.id')
        return ret
Beispiel #7
0
 def __init__(self, url, username, password, space):
     self.confluence = Confluence(url, username=username, password=password)
     spaces = self.confluence.get_all_spaces(start=0, limit=500)
     if any(s for s in spaces if s["name"] == space):
         self.space = space
     else:
         raise ValueError("{} is not valid Confluence Space".format(space))
Beispiel #8
0
    def __init__(
            self, url, username, api_token,
            page_title_prefix, markdown_dir, db_path, space, parent_pageid,
            force_update=False, force_delete=False, skip_update=False,
            verbose=False):

        self.api = Confluence(url=url, username=username, password=api_token)
        self.page_title_prefix = page_title_prefix
        self.markdown_dir = markdown_dir
        self.kv = KeyValue(db_path)
        self.space = space
        self.parent_pageid = parent_pageid
        self.force_update = force_update
        self.force_delete = force_delete
        self.skip_update = skip_update
        self.confluence_renderer = ConfluenceRenderer(verbose)
        self.renderer = mistune.create_markdown(
            renderer=self.confluence_renderer,
            plugins=[
                plugin_front_matter,
                DirectiveInclude(),
                HugoRefLinkPlugin(self.markdown_dir),
                'strikethrough',
                'footnotes',
                'table',
                'url',
                Admonition(),
                plugin_html_comment,
            ]
        )
    def test_confluence_attach_file_2(self):
        credentials = None

        try:
            with open(self.secret_file) as json_file:
                credentials = json.load(json_file)
        except Exception as err:
            self.fail("[{0}]: {1}".format(self.secret_file, err))

        confluence = Confluence(
            url=credentials["host"],
            username=credentials["username"],
            password=credentials["password"],
        )

        # individual configuration
        space = "SAN"
        title = "atlassian-python-rest-api-wrapper"

        # TODO: check if page are exists

        fd, filename = tempfile.mkstemp("w")
        os.write(fd, b"Hello World - Version 1")

        name = os.path.basename(tempfile.mktemp()) + ".txt"

        # upload a new file
        result = confluence.attach_file(
            filename,
            name,
            content_type="text/plain",
            title=title,
            space=space,
            comment="upload from unittest",
        )

        # attach_file() returns: {'results': [{'id': 'att144005326', 'type': 'attachment', ...
        self.assertTrue("results" in result)
        self.assertFalse("statusCode" in result)

        # upload a new version of an existing file
        os.lseek(fd, 0, 0)
        os.write(fd, b"Hello Universe - Version 2")
        result = confluence.attach_file(
            filename,
            name,
            content_type="text/plain",
            title=title,
            space=space,
            comment="upload from unittest",
        )

        # attach_file() returns: {'id': 'att144005326', 'type': 'attachment', ...
        self.assertTrue("id" in result)
        self.assertFalse("statusCode" in result)

        os.close(fd)
        os.remove(filename)
Beispiel #10
0
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
Beispiel #11
0
 def __init__(self):
     super().__init__()
     self.environment = Environment.Environment()
     self.logger = Logger.Logger()
     self.confluence = Confluence(
         self.environment.get_endpoint_confluence_host(),
         username=self.environment.get_endpoint_confluence_user(),
         password=self.environment.get_endpoint_confluence_password())
     self.card_transfer = CardTransfer.CardTransfer()
     self.regex = RegEx.RegEx()
 def _connect(self, host: str, login: str, password: str, verify_ssl: bool) -> Confluence:
     """Connect to Confluence server and test connection"""
     self.logger.debug(f'Trying to connect to confluence server at {host}')
     host = host.rstrip('/')
     self.con = Confluence(host, login, password, verify_ssl=verify_ssl)
     try:
         res = self.con.get('rest/api/space')
     except UnicodeEncodeError:
         raise RuntimeError('Sorry, non-ACSII passwords are not supported')
     if isinstance(res, str) or 'statusCode' in res:
         raise RuntimeError(f'Cannot connect to {host}:\n{res}')
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
Beispiel #14
0
    def __init__(self, space="", url="", username="", token="", parent=None):
        self.parent = parent
        self.space = space

        # if not all([space, url, username, token]):
        #     raise ConfluenceAPIError("Must assigne a space, url, unername and token")

        # Define atlassian api connection
        self.conn = Confluence(url=url,
                               username=username,
                               password=token,
                               cloud=True)
Beispiel #15
0
def create_nbpm_collab_page(cir_title, creds):
    collab = Confluence(url='https://collab.test.net/',
                        username=creds['user'],
                        password=creds['password'])
    cir_date = datetime.now().strftime("%Y-%m-%d")
    cir_title = cir_title
    body_text = '''    '''

    page = collab.create_page(space="NBPM",
                              parent_id=143085345,
                              title=cir_title,
                              body=body_text)
Beispiel #16
0
    def test_confluence_attach_file_2(self):
        credentials = None

        try:
            with open(self.secret_file) as json_file:
                credentials = json.load(json_file)
        except Exception as err:
            self.fail('[{0}]: {1}'.format(self.secret_file, err))

        confluence = Confluence(url=credentials['host'],
                                username=credentials['username'],
                                password=credentials['password'])

        # individual configuration
        space = 'SAN'
        title = 'atlassian-python-rest-api-wrapper'

        # TODO: check if page are exists

        fd, filename = tempfile.mkstemp('w')
        os.write(fd, b'Hello World - Version 1')

        name = os.path.basename(tempfile.mktemp()) + ".txt"

        # upload a new file
        result = confluence.attach_file(filename,
                                        name,
                                        content_type='text/plain',
                                        title=title,
                                        space=space,
                                        comment='upload from unittest')

        # attach_file() returns: {'results': [{'id': 'att144005326', 'type': 'attachment', ...
        self.assertTrue('results' in result)
        self.assertFalse('statusCode' in result)

        # upload a new version of an existing file
        os.lseek(fd, 0, 0)
        os.write(fd, b'Hello Universe - Version 2')
        result = confluence.attach_file(filename,
                                        name,
                                        content_type='text/plain',
                                        title=title,
                                        space=space,
                                        comment='upload from unittest')

        # attach_file() returns: {'id': 'att144005326', 'type': 'attachment', ...
        self.assertTrue('id' in result)
        self.assertFalse('statusCode' in result)

        os.close(fd)
        os.remove(filename)
    def test_confluence_attach_content(self):
        credentials = None

        try:
            with open(self.secret_file) as json_file:
                credentials = json.load(json_file)
        except Exception as err:
            self.fail("[{0}]: {1}".format(self.secret_file, err))

        confluence = Confluence(
            url=credentials["host"],
            username=credentials["username"],
            password=credentials["password"],
        )

        # individual configuration
        space = "SAN"
        title = "atlassian-python-rest-api-wrapper"

        attachment_name = os.path.basename(tempfile.mktemp())

        # upload a new file
        content = b"Hello World - Version 1"
        result = confluence.attach_content(
            content,
            attachment_name,
            "text/plain",
            title=title,
            space=space,
            comment="upload from unittest",
        )

        # attach_file() returns: {'results': [{'id': 'att144005326', 'type': 'attachment', ...
        self.assertTrue("results" in result)
        self.assertFalse("statusCode" in result)

        # upload a new version of an existing file
        content = b"Hello Universe - Version 2"
        result = confluence.attach_content(
            content,
            attachment_name,
            "text/plain",
            title=title,
            space=space,
            comment="upload from unittest",
        )

        # attach_file() returns: {'id': 'att144005326', 'type': 'attachment', ...
        self.assertTrue("id" in result)
        self.assertFalse("statusCode" in result)
Beispiel #18
0
 def _establish_confluence_connection(self):
     """
     Setup the confluence object to be interacted with later
     :return:
     """
     # URL needs to be in the settingsmeta.yaml
     # confluence username needs to be in the settingsmeta.yaml
     # confluence password needs to be in the settingsmeta.yaml
     self.username = self.settings.get('user_name')
     self.password = self.settings.get('password')
     self.confluence_url = self.settings.get('confluence_url')
     self.confluence = Confluence(url=self.confluence_url,
                                  username=self.username,
                                  password=self.password)
 def __init__(self, project_key, config, plugin_config):
     """
     :param project_key: the project in which the runnable executes
     :param config: the dict of the configuration of the object
     :param plugin_config: contains the plugin settings
     """
     self.project_key = project_key
     self.config = config
     confluence_login = self.config.get("confluence_login", None)
     if confluence_login is None:
         raise Exception("No Confluence login is currently set.")
     self.confluence_username = confluence_login.get(
         "confluence_username", None)
     self.assert_confluence_username()
     self.confluence_password = confluence_login.get(
         "confluence_password", None)
     self.assert_confluence_password()
     self.confluence_url = self.format_confluence_url(
         confluence_login.get("server_type", None),
         confluence_login.get("url", None),
         confluence_login.get("orgname", None))
     self.confluence_space_key = confluence_login.get(
         "confluence_space_key", None)
     self.assert_space_key()
     self.confluence_space_name = confluence_login.get(
         "confluence_space_name", self.confluence_space_key)
     if self.confluence_space_name == "":
         self.confluence_space_name = self.confluence_space_key
     self.check_space_key_format()
     self.client = dataiku.api_client()
     try:
         self.studio_external_url = self.client.get_general_settings(
         ).get_raw()['studioExternalUrl']
         assert (self.studio_external_url not in (None, ''))
     except Exception as err:
         logger.error("studioExternalUrl not set :{}".format(err))
         raise Exception(
             "Please set the DSS location URL in Administration > Settings > Notifications & Integrations > DSS Location > DSS URL"
         )
     self.wiki = DSSWiki(self.client, self.project_key)
     self.wiki_settings = self.wiki.get_settings()
     self.taxonomy = self.wiki_settings.get_taxonomy()
     self.articles = self.wiki.list_articles()
     self.space_homepage_id = None
     self.confluence = Confluence(url=self.confluence_url,
                                  username=self.confluence_username,
                                  password=self.confluence_password)
     self.assert_logged_in()
     self.progress = 0
Beispiel #20
0
def update_page(cell, content):
    """ update method """
    cipher = Security('ec2cli')
    server, user, passwd, parent_id, page_id, title, response, region, product = config(
        cell)
    confluence = Confluence(url=server,
                            username=user,
                            password=cipher.decrypt(passwd))

    confluence.update_page(parent_id=parent_id,
                           page_id=page_id,
                           title=title,
                           body=content)

    return response
Beispiel #21
0
def helperFunc1(confluenceUrl, jiraUrl):
    global confluence
    global jira
    if nameEnter.get() and not nameEnter.get().isspace():
        confluenceName = nameEnter.get()
        confluencePass = passwordEnter.get()
        confluence = Confluence(url=confluenceUrl,
                                username=confluenceName,
                                password=confluencePass)
        #try:
        jira = JIRA(jiraUrl, auth=(nameEnter.get(), passwordEnter.get()))
        textBox.insert(END, "logged in as " + nameEnter.get() + "\n")
        window.deiconify()
        top.destroy()
        jqlSearch = f'project=HR and status = open order by "cf[11200]" asc'
        issues = jira.search_issues(jqlSearch)
        for issue in issues:
            if (str(issue.fields.status) == 'Open'
                    and not issue.fields.customfield_11705):
                openBox.insert(END, issue.fields.summary)
        openBox.select_set(0)
        openBox.bind("<Double-Button-1>", OnDouble)
        #except Exception as e:
        #print e.status_code, e.text
        #    messageBox.showinfo("Login Failed","Login Failed. Please try again\n(You may have trigger captcha from too many failed login. Please login to jira directly and clear it)")
    else:
        messageBox.showinfo("Failure",
                            "Please enter both username and password")
Beispiel #22
0
class BaseReport:

    def __init__(self, fix_version):
        self.fix_version = fix_version
        self.confluence = Confluence(url=confluence_url, **user_credentials)

    @property
    def release_page_id(self):
        return self._find_child_id(hasdk_releases, f"{self.fix_version} - SDK1.X")

    @property
    def rc_release_page_id(self):
        return self._find_child_id(self.release_page_id, f"RC - {self.fix_version} - SDK1.X")

    def _find_child_id(self, parent_id: int, part_of_child_name: str, child_limit=300) -> int:
        children = self.confluence.get_page_child_by_type(parent_id, limit=child_limit)
        log.info(f"children -> {children}")
        for child in children:
            if part_of_child_name in child.get('title'):
                return child.get('id')
        return 0

    def create_page(self): raise NotImplemented

    def _page_title(self): raise NotImplemented

    def fill_page_template(self): raise NotImplemented
def acquire_conf_connection(url, username=None, password=None):
    username = username if username is not None else getpass.getuser()
    password = password if password is not None else getpass.getpass(
        "Please insert your password >> ")
    return Confluence(url=url,
                      api_root='wiki/rest/api',
                      username=username,
                      password=password)
Beispiel #24
0
    def __init__(self, credentials, path):
        self.remote = Confluence(url=credentials[0],
                                 username=credentials[1],
                                 password=credentials[2])

        def converter_to_local_key(key):
            if isinstance(key, tuple):
                return 'name_' + key[0] + key[1]
            else:
                return 'id_' + key

        self.cached = CachedDataProvider(
            self, path, converter_to_local_key=converter_to_local_key)
        self.simplified = CachedDataProvider(
            ConfluenceSimplifiedTextProvider(self.cached),
            path + '.simplified',
            converter_to_local_key=converter_to_local_key)
Beispiel #25
0
def login_confluence():
    # log in credentials for confluence api
    confluence = Confluence(
        # url='https://usmai-wwwdev.lib.umd.edu/portal',
        url='https://usmai-wwwdev.lib.umd.edu/portal',
        username='******',
        password='******')
    return confluence
Beispiel #26
0
def post_to_convert_api(confluence: Confluence, text: str) -> str:
    url = "rest/tinymce/1/markdownxhtmlconverter"
    # the endpoint returns plain text, need to redefine the default header
    headers = {"Content-Type": "application/json"}
    # Keep until https://github.com/atlassian-api/atlassian-python-api/pull/684 is released
    original_advanced_mode = confluence.advanced_mode
    if confluence.advanced_mode is False or confluence.advanced_mode is None:
        confluence.advanced_mode = True

    response: Response = confluence.post(url,
                                         data={"wiki": text},
                                         headers=headers)
    # No way to trigger failure for this during tests
    response.raise_for_status()  # pragma: no cover

    confluence.advanced_mode = original_advanced_mode

    return response.text
 def __init__(self,
              aepreq_jira_key,
              fix_version,
              cycle_name,
              map_version,
              map_revision,
              map_region="World",
              platform="Linux64"):
     self.aepreq_key = aepreq_jira_key
     self.fix_version = fix_version
     self.cycle_name = cycle_name
     self.map_version = map_version
     self.map_revision = map_revision
     self.map_region = map_region
     self.platform = platform
     self.zapi = ZephyrAPI()
     self.confluence = Confluence(url='https://confluence.in.here.com',
                                  **user_credentials)
Beispiel #28
0
    def test_confluence_attach_content(self):
        credentials = None

        try:
            with open(self.secret_file) as json_file:
                credentials = json.load(json_file)
        except Exception as err:
            self.fail('[{0}]: {1}'.format(self.secret_file, err))

        confluence = Confluence(url=credentials['host'],
                                username=credentials['username'],
                                password=credentials['password'])

        # individual configuration
        space = 'SAN'
        title = 'atlassian-python-rest-api-wrapper'

        attachment_name = os.path.basename(tempfile.mktemp())

        # upload a new file
        content = b'Hello World - Version 1'
        result = confluence.attach_content(content,
                                           attachment_name,
                                           'text/plain',
                                           title=title,
                                           space=space,
                                           comment='upload from unittest')

        # attach_file() returns: {'results': [{'id': 'att144005326', 'type': 'attachment', ...
        self.assertTrue('results' in result)
        self.assertFalse('statusCode' in result)

        # upload a new version of an existing file
        content = b'Hello Universe - Version 2'
        result = confluence.attach_content(content,
                                           attachment_name,
                                           'text/plain',
                                           title=title,
                                           space=space,
                                           comment='upload from unittest')

        # attach_file() returns: {'id': 'att144005326', 'type': 'attachment', ...
        self.assertTrue('id' in result)
        self.assertFalse('statusCode' in result)
Beispiel #29
0
def logIntoConfluence():
    """Temporary solution for Confluence login"""
    username = '******'
    password = '******'m not exposing my password. Gotta wait till I\
    figure out how to retrieve logged-in user details first!'
    confluence = Confluence(
        url='https://confluence.cis.unimelb.edu.au:8443/',
        username=username,
        password=password
    )
    return confluence
Beispiel #30
0
def confluence_get_page():
    #Конфиг
    base_path = os.path.dirname(os.path.abspath(__file__))
    #применяем конфигурацию по умолчанию
    #config_path_default = os.path.join(base_path, "dafault.conf")
    config_path = os.path.join(base_path, "config.conf")
    if os.path.exists(config_path):
        cfg = configparser.ConfigParser()
        #cfg.read(config_path_default)
        cfg.read(config_path)
    else:
        print(
            "Конфиг не обнаружен! см. документацию по настройке https://github.com/AndreyAgafonov/python/tree/master/birthday"
        )
        sys.exit(1)
    # Парсим конфиг файл
    section = "confluence"
    confluence_url = cfg.get(section, "confluence_connection_string")
    confluence_pageid = cfg.get(section, "confluence_pageid")
    confluence_user = cfg.get(section, "confluence_user")
    confluence_passwd = cfg.get(section, "confluence_passwd")

    section = "general"
    general_col_name = cfg.get(section, "column_date_of_birth")
    # Подключение к конфлюенсе
    confluence = Confluence(url=confluence_url,
                            username=confluence_user,
                            password=confluence_passwd)
    content1 = confluence.get_page_by_id(confluence_pageid,
                                         expand="body.storage")
    ##Первая колонка  это порядковый номер -  используем ее как индекс index_col=0
    ##Заголовок в первой строке - ее тоже не учитываем header=0
    ##
    df_list = pd.read_html(content1['body']['storage']['value'],
                           header=0,
                           index_col=0,
                           na_values=['No Acquirer'],
                           converters={general_col_name: str})
    table = df_list[0]
    table.index.name = "Number"
    return table
Beispiel #31
0
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}')
# coding: utf8
import logging
from atlassian import Confluence
from atlassian import Jira

logging.basicConfig(level=logging.DEBUG, format='[%(asctime).19s] [%(levelname)s] %(message)s')
logging.getLogger('requests').setLevel(logging.WARNING)
log = logging.getLogger('jira-projects-administrators')

jira = Jira(
    url='http://localhost:8080',
    username='******',
    password='******')

confluence = Confluence(
    url='http://localhost:8090',
    username='******',
    password='******')

html = ["""<table>
                <tr>
                    <th>Project Key</th>
                    <th>Project Name</th>
                    <th>Leader</th>
                    <th>Email</th>
                </tr>"""]


for data in jira.project_leaders():
    log.info('{project_key} leader is {lead_name} <{lead_email}>'.format(**data))
    row = """<tr>
                <td>{project_key}</td>
Beispiel #33
0
#! /usr/bin/env python3

import re

from atlassian import Confluence
from six.moves.urllib.parse import urljoin
from bs4 import BeautifulSoup

WIKI_URL = "https://wiki.4paradigm.com"

confluence = Confluence(
        url=WIKI_URL,
        username="******",
        password="******")

ret = confluence.get_page_by_id("36220156", expand="body")
web_view_url = ret["_links"]["webui"]
url = urljoin(confluence.url, web_view_url)
resp = confluence._session.request(
        method="GET",
        url=url,
        auth=(confluence.username, confluence.password),
        timeout=confluence.timeout,
        verify=confluence.verify_ssl)

# p = re.compile(r"docker02:35000[a-zA-Z0-9./]+<")
p = re.compile(r"docker02:35000[-.:/a-zA-Z0-9]+")

soup = BeautifulSoup(resp.text, "html.parser")
table = soup.find(
        "table", attrs={"class": "wrapped relative-table confluenceTable"})
from pprint import pprint
from atlassian import Confluence


confluence = Confluence(
    url='http://localhost:8090',
    username='******',
    password='******')

status = confluence.create_page(
    space='DEMO',
    title='This is the title',
    body='This is the body')

pprint(status)
# coding: utf8
from atlassian import Confluence

"""This example shows how to export pages"""

confluence = Confluence(
    url='https://test.atlassian.net/wiki',
    username='******',
    password='******',
    api_version='cloud'
)

if __name__ == '__main__':
    space = 'TEST'
    page_title = 'Test'
    page_id = confluence.get_page_id(space, page_title)
    content = confluence.export_page(page_id)
    with open(page_title + ".pdf", 'wb') as pdf_file:
        pdf_file.write(content)
        pdf_file.close()
        print("Completed")
from atlassian import Confluence

""" How to reindex the Confluence instance """

confluence = Confluence(
    url='http://localhost:8090',
    username='******',
    password='******')


if confluence.get_reindex_status().get('finished'):
    print("Start reindex")
    confluence.reindex()
from pprint import pprint
from atlassian import Confluence


confluence = Confluence(url="http://localhost:8090", username="******", password="******")

status = confluence.update_page(page_id=123456, title="This is the new title", body="This is the new body")

pprint(status)
logging.basicConfig(level=logging.DEBUG, format="[%(asctime).19s] [%(levelname)s] %(message)s")
logging.getLogger("requests").setLevel(logging.WARNING)
log = logging.getLogger("jira-projects-administrators")


jira = Jira(
    url="http://localhost:8000/",
    username="******",
    password="******")

html = "<table><tr><th>Project Key</th><th>Project Name</th><th>Leader</th><th>Email</th></tr>"

for data in jira.project_leaders():
    log.info("{project_key} leader is {lead_name} <{lead_email}>".format(**data))
    html += "<tr><td>{project_key}</td><td>{project_name}<td></td>{lead_name}<td></td><a href='mailto:{lead_email}'>{lead_email}</a></td></tr>".format(**data)

html += "</table><p></p><p></p>"
html += "<p>Autogenerated with <a href='http://localhost:7999/projects/AGILE/repos/devops-utils-jira/browse/bin/jira-projects-administrators.py'>this script</a></p>"

confluence = Confluence(
    url="http://localhost:8090/",
    username="******",
    password="******")

confluence.update_page(
    page_id=13207798,
    parent_id=7471197,
    title="Administratorzy JIRA",
    body=html)

log.info("Confluence Page Created with JRIA Administrators at: http://localhost:8095/pages/viewpage.action?pageId=13207798")
# 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)
# coding: utf8
from atlassian import Confluence

confluence = Confluence(
    url='http://localhost:8090',
    username='******',
    password='******')

status = confluence.update_page(
    parent_id=None,
    page_id=123456,
    title='This is the new title',
    body='This is the new body')

print(status)