使用Python和API更新Confluence页面的问题

问题描述 投票:0回答:1

我正在通过python和Confluence API更新Confluence页面。

我找到了一个将数据写入我的页面的功能,不幸的是它创建了一个包含我的数据的新页面,旧页面变成了一个存档版本。

我一直在搜索参考资料,看不出我得到新页面的原因,而不是将数据附加到页面的末尾。我能想到的唯一解决方案是复制正文并将新数据附加到其中,然后创建新页面......但我认为应该有一种方法可以追加。

我发现/正在利用的写函数代码如下:

def write_data(auth, html, pageid, title = None):


    info = get_page_info(auth, pageid)
    print ("after get page info")
    ver = int(info['version']['number']) + 1

    ancestors = get_page_ancestors(auth, pageid)

    anc = ancestors[-1]
    del anc['_links']
    del anc['_expandable']
    del anc['extensions']

    if title is not None:
        info['title'] = title

    data = {
        'id' : str(pageid),
        'type' : 'page',
        'title' : info['title'],
        'version' : {'number' : ver},
        'ancestors' : [anc],
        'body'  : {
            'storage' :
            {
                'representation' : 'storage',
                'value' : str(html),
            }
        }
    }

    data = json.dumps(data)
    pprint (data)
    url = '{base}/{pageid}'.format(base = BASE_URL, pageid = pageid)

    r = requests.put(
        url,
        data = data,
        auth = auth,
        headers = { 'Content-Type' : 'application/json' }
    )

    r.raise_for_status()

我开始认为复制/附加到身体是可选的,但希望其他人遇到此问题。

python confluence confluence-rest-api
1个回答
0
投票

不是一个优雅的解决方案,但我去复制旧的身体和追加选项。

基本上,写了一个简单的函数来返回现有的body:

def get_page_content(auth, pageid):

    url = '{base}/{pageid}?expand=body.storage'.format(
        base = BASE_URL,
        pageid = pageid)

    r = requests.get(url, auth = auth)
    r.raise_for_status()

    return (r.json()['body']['storage']['value'])

在此示例中,只需将(+ =)一个新字符串附加到现有主体。

def write_data(auth, html, pageid, title = None):

    info = get_page_info(auth, pageid)
    page_content = get_page_content(auth, pageid)
    ver = int(info['version']['number']) + 1

    ancestors = get_page_ancestors(auth, pageid)

    anc = ancestors[-1]
    del anc['_links']
    del anc['_expandable']
    del anc['extensions']

    page_content += "\n\n"
    page_content += html

    if title is not None:
        info['title'] = title

    data = {
        'id' : str(pageid),
        'type' : 'page',
        'title' : info['title'],
        'version' : {'number' : ver},
        'ancestors' : [anc],
        'body'  : {
            'storage' :
            {
                'representation' : 'storage',
                'value' : str(page_content),
            }
        }
    }

    data = json.dumps(data)
    url = '{base}/{pageid}'.format(base = BASE_URL, pageid = pageid)

    r = requests.put(
        url,
        data = data,
        auth = auth,
        headers = { 'Content-Type' : 'application/json' }
    )

    r.raise_for_status()

    print "Wrote '%s' version %d" % (info['title'], ver)
    print "URL: %s%d" % (VIEW_URL, pageid)

应该注意,由于这是一个汇合体的帖子,传递的文本是html。换行的'\ n'不起作用,你需要通过'<br \>'等...

如果有人有更优雅的解决方案,欢迎提出建议。

Dan.

© www.soinside.com 2019 - 2024. All rights reserved.