You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python结合XWiki API合并页面内容而非直接替换?

如何用Python脚本将.txt内容追加到XWiki页面而非替换原有内容?

我写了一段Python脚本,用来把.txt文件内容写入XWiki页面,但现在脚本会直接替换页面原有内容。有没有办法合并新旧内容,保留原有内容并把新内容追加进去?

参考代码:

import requests

url = "http://server:port/xwiki/rest/wikis/xwiki/spaces/Sandbox/pages/TestPage1/"
file_path = r"example.txt"

username = "username"
password = "password"

headers = {
    "Content-Type": "text/plain"
}

with open(file_path, "rb") as file:
    response = requests.put(url, headers=headers, data=file, auth=(username, password))

if response.status_code == 201:
    print("The Page was successfully created.")
elif response.status_code == 202:
    print("The page was successfully updated.")
elif response.status_code == 304:
    print("The Page was not modified.")
elif response.status_code == 401:
    print("The user is not authorized.")
else:
    print("Error uploading the data:", response.status_code)

我已经查阅了3次XWiki官方RESTful API文档,没找到合并新旧内容的相关说明,可能有遗漏?求建议!


解决方案

要实现追加内容,需要先获取页面原有内容,再将新内容拼接后重新上传,步骤如下:

  • 获取页面现有内容:用GET请求访问页面的REST接口,设置Accept: text/plain头以获取纯文本格式的内容。
  • 读取新内容:从本地.txt文件读取要追加的内容。
  • 合并内容:将现有内容和新内容拼接(可自定义分隔符,比如换行、分割线)。
  • 上传合并后的内容:用PUT请求将合并后的内容上传回页面。

修改后的代码示例:

import requests

url = "http://server:port/xwiki/rest/wikis/xwiki/spaces/Sandbox/pages/TestPage1/"
file_path = r"example.txt"

username = "username"
password = "password"

# 获取页面现有内容
get_headers = {
    "Accept": "text/plain"
}
get_response = requests.get(url, headers=get_headers, auth=(username, password))
existing_content = get_response.text if get_response.status_code == 200 else ""

# 读取新内容
with open(file_path, "r", encoding="utf-8") as file:
    new_content = file.read()

# 合并内容(用换行+分割线分隔,可按需调整)
merged_content = f"{existing_content}\n\n---\n\n{new_content}"

# 上传合并后的内容
put_headers = {
    "Content-Type": "text/plain"
}
put_response = requests.put(url, headers=put_headers, data=merged_content.encode("utf-8"), auth=(username, password))

# 处理响应
if put_response.status_code == 201:
    print("页面创建成功。")
elif put_response.status_code == 202:
    print("页面更新成功(内容已追加)。")
elif put_response.status_code == 304:
    print("页面未修改。")
elif put_response.status_code == 401:
    print("用户未授权。")
else:
    print(f"上传数据出错:{put_response.status_code}")

注意事项

  • 若页面不存在(首次创建),GET请求会返回404,此时existing_content为空,直接上传新内容即可,不影响逻辑。
  • 注意编码统一,读取文件和上传时使用UTF-8编码,避免乱码。
  • 可根据需求调整内容合并格式,比如添加时间戳、自定义分隔符等。

内容的提问来源于stack exchange,提问作者IShafigh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 13:10:11