我正在编写一个Python脚本来创建一个新的Confluence页面,并使用html文件中的内容更新页面。下面是我的代码。我使用的是汇流版本5.8.10
import argparse
import getpass
import sys
import json
import keyring
import requests
#-----------------------------------------------------------------------------
# Globals
BASE_URL = "https://wiki.hurry.com/rest/api/content"
def pprint(data):
'''
Pretty prints json data.
'''
print json.dumps(
data,
sort_keys = True,
indent = 4,
separators = (', ', ' : '))
def write_data(auth, html, title):
ver = 'TEST'
data = {
'type' : 'page',
'title' : str(title),
'space' : {'key' : TEST},
'body' : {
'storage' :
{
'representation' : 'storage',
'value' : str(html),
}
}
}
data = json.dumps(data)
print data
url = '{base}/?os_authType=basic'.format(base = BASE_URL)
print url
r = requests.post(
url,
data = data,
auth = auth,
headers = { 'Content-Type' : 'application/json' }
)
r.raise_for_status()
def get_login(username = None):
'''
Get the password for username out of the keyring.
'''
if username is None:
username = getpass.getuser()
passwd = keyring.get_password('confluence_script', username)
if passwd is None:
passwd = getpass.getpass()
keyring.set_password('confluence_script', username, passwd)
return (username, passwd)
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
"-u",
"--user",
default = getpass.getuser(),
help = "Specify the username to log into Confluence")
parser.add_argument(
"-t",
"--title",
default = None,
type = str,
help = "Specify a new title")
parser.add_argument(
"-f",
"--file",
default = None,
type = str,
help = "Write the contents of FILE to the confluence page")
parser.add_argument(
"html",
type = str,
default = None,
nargs = '?',
help = "Write the immediate html string to confluence page")
options = parser.parse_args()
auth = get_login(options.user)
if options.html is not None and options.file is not None:
raise RuntimeError(
"Can't specify both a file and immediate html to write to page!")
if options.html:
html = options.html
else:
with open(options.file, 'r') as fd:
html = fd.read()
write_data(auth, html, options.title)
if __name__ == "__main__" : main()
以下是我得到的错误
r.raise_for_status()
File "C:\Python27\lib\site-packages\requests\models.py", line 928, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://wiki.hurry.com/rest/api/content/?os_authType=basic
有人能让我知道我在这里做错了什么吗?
答案 0 :(得分:1)
根据您遇到的错误400 Client Error
,问题肯定在您身边。 RESTful API通常需要JSON数据,而不是HTML。
确保您发送的数据以及您使用请求的方式,因为请求正在执行其他内容"在幕后"取决于您传递给某些方法的内容(例如,将json
参数添加到post
会自动在您的请求中附加Content-Type: application/json
标题。)
另外,请务必了解HTTP response codes;)