How can I create a new page to confluence with Pyt

2020-03-04 06:51发布

I am trying to create a new page into confluence using Python's xmlrpclib. I already know how to update content of an existing page, but how can I create a totally new page?

I have used following script to update content:

import xmlrpclib

CONFLUENCE_URL='https://wiki.*ownURL*/rpc/xmlrpc'

def update_confluence(user, pwd, pageid, newcontent):    
    client = xmlrpclib.Server(CONFLUENCE_URL,verbose=0)      
    authToken=client.confluence2.login(user,pwd)
    page = client.confluence2.getPage(authToken, pageid)
    page['content'] = newcontent
    cient.confluence2.storePage(authToken, page)
    client.confluence2.logout(authToken)

and that works well when updating content. But problem is that somehow I need to resolve pageID when creating a new page and I have no idea how to do that.

Are there any other ways to create new page?

3条回答
时光不老,我们不散
2楼-- · 2020-03-04 07:32

I dont know Python, but can do this with a REST call:

echo '{"type":"page","ancestors":[{"type":"page","id":'$CONFLUENCE_PARENT_PAGE'}],"title":"'$PAGE_NAME'","space":{"key":"'$CONFLUENCE_SPACE'"},"body":{"storage":{"value":"'$CONTENT'","representation":"storage"}}}' > body.json

curl --globoff --insecure --silent -u ${CONFLUENCE_USER}:${CONFLUENCE_PASSWORD} -X POST -H 'Content-Type: application/json' --data @body.json $CONFLUENCE_REST_API_URL

The confluence rest api url looks something like this: https://confluence.yourdomain.com/rest/api/content/

Basically the answer to your question is you need to send the parent page as an ancestor when creating a brand new page.

查看更多
Bombasti
3楼-- · 2020-03-04 07:39

You can create pages using the Confluence REST API: https://docs.atlassian.com/atlassian-confluence/REST/latest-server/

Here is an example that works in Python3. You'll need to know the parent page id.

import requests
import json
import base64

# Set the confluence User and Password for authentication
user = 'USER'
password = 'PASSWORD'

# Set the title and content of the page to create
page_title = 'My New Page'
page_html = '<p>This page was created with Python!</p>'

# You need to know the parent page id and space key.
# You can use the /content API to search for these values.
# Parent Page example http://example.com/display/ABC/Cheese
# Search example: http://example.com/rest/api/content?title=Cheese
parent_page_id = 123456789
space_key = 'ABC'

# Request URL - API for creating a new page as a child of another page
url = 'http://example.com/rest/api/content/'

# Create the basic auth for use in the authentication header
auth = base64.b64encode(b'{}:{}'.format(user, password))

# Request Headers
headers = {
    'Authorization': 'Basic {}'.format(auth),
    'Content-Type': 'application/json',
}

# Request body
data = {
    'type': 'page',
    'title': page_title,
    'ancestors': [{'id':parent_page_id}],
    'space': {'key':space_key},
    'body': {
        'storage':{
            'value': page_html,
            'representation':'storage',
        }
    }
}

# We're ready to call the api
try:

    r = requests.post(url=url, data=json.dumps(data), headers=headers)

    # Consider any status other than 2xx an error
    if not r.status_code // 100 == 2:
        print("Error: Unexpected response {}".format(r))
    else:
        print('Page Created!')

except requests.exceptions.RequestException as e:

    # A serious problem happened, like an SSLError or InvalidURL
    print("Error: {}".format(e))
查看更多
Animai°情兽
4楼-- · 2020-03-04 07:55

Answer of "J. Antunes" is correct, but it took a long time for me to find the APIs, pageIds etc. This answer will give you a step by step guide on how to achieve this with API Tokens.

Step 1: Generate API Token in Confluence.

In the confluence page, go to Settings and click on password. Click on "Create and manage API tokens" and get the token. {TOKEN}

enter image description here

Step 2: Find the parent page you want to create a child page at

Go to get the parent page ID, and find the {Parent Page ID}

Step 3: Get the Space Key

On confluence, go to Space Settings, and find the Space Key mentioned.{SPACE KEY}

enter image description here

Step 4: Now get started with the code

import requests
import json
from requests.auth import HTTPBasicAuth

# set auth token and get the basic auth code
auth_token = "{TOKEN}"
basic_auth = HTTPBasicAuth('{email you use to log in}', auth_token)

# Set the title and content of the page to create
page_title = 'My New Page'
page_html = '<p>This page was created with Python!</p>'

parent_page_id = {Parent Page ID}
space_key = '{SPACE KEY}'

# get the confluence home page url for your organization {confluence_home_page}
url = '{confluence_home_page}/rest/api/content/'

# 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':'storage',
        }
    }
}

# We're ready to call the api
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))
    else:
        print('Page Created!')

except requests.exceptions.RequestException as e:

    # A serious problem happened, like an SSLError or InvalidURL
    print("Error: {}".format(e))
查看更多
登录 后发表回答