【发布时间】:2017-08-18 09:12:46
【问题描述】:
我正在尝试使用 python 请求访问 Atlassian Confluence REST API。
我已经成功调用了一个GET api,但是当我调用PUT更新一个confluence页面时,它返回200,但没有更新页面。
我使用 chrome::YARC 来验证 API 是否正常工作(确实如此)。尝试调试了一段时间后,我恢复尝试使用 urllib3,效果很好。
我真的很想使用请求,但经过数小时的调试、Google 等尝试,我终生无法弄清楚这一点。
我正在运行 Mac/Python3:
$ uname -a
Darwin mylaptop.local 16.7.0 Darwin Kernel Version 16.7.0: Thu Jun 15 17:36:27 PDT 2017; root:xnu-3789.70.16~2/RELEASE_X86_64 x86_64
$ python3 --version
Python 3.6.1
这是我的代码,显示了我正在尝试的所有三种方式(两个请求和一个 urllib3):
def update(self, spaceKey, pageTitle, newContent, contentType='storage'):
if contentType not in ('storage', 'wiki', 'plain'):
raise ValueError("Invalid contentType={}".format(contentType))
# Get current page info
self._refreshPage(spaceKey, pageTitle) # I retrieve it before I update it.
orig_version = self.version
# Content already same as requested content. Do nothing
if self.wiki == newContent:
return
data_dict = {
'type' : 'page',
'version' : {'number' : self.version + 1},
'body' : {
contentType : {
'representation' : contentType,
'value' : str(newContent)
}
}
}
data_json = json.dumps(data_dict).encode('utf-8')
put = 'urllib3' #for now until I figure out why requests.put() doesn't work
enable_http_logging()
if put == 'requests':
r = self._cs.api.content(self.id).PUT(json=data_dict)
r.raise_for_status()
elif put == 'urllib3':
urllib3.disable_warnings() # I know, you can quit your whining now!!!
headers = { 'Content-Type' : 'application/json;charset=utf-8' }
auth_header = urllib3.util.make_headers(basic_auth=":".join(self._cs.session.auth))
headers = {**headers, **auth_header}
http = urllib3.PoolManager()
r = http.request('PUT', str(self._cs.api.content(self.id)), body=data_json, headers=headers)
else:
raise ValueError("Huh? Unknown put type: {}".format(put))
enable_http_logging(False)
# Verify page was updated
self._refreshPage(spaceKey, pageTitle) # Check for changes
if self.version != orig_version + 1:
raise RuntimeError("Page not updated. Still at version {}".format(self.version))
if self.wiki != newContent:
raise RuntimeError("Page version updated, but not content.")
任何帮助都会很棒。
更新 1:添加请求转储
-----------START-----------
PUT http://confluence.myco.com/rest/api/content/101904815
User-Agent: python-requests/2.18.4
Accept-Encoding: gzip, deflate
Accept: */*
Connection: keep-alive
Content-Length: 141
Content-Type: application/json
Authorization: Basic <auth-token-here>==
b'{"type": "page", "version": {"number": 17}, "body": {"storage": {"representation": "storage", "value": "new body here version version 17"}}}'
【问题讨论】:
-
我以前用过这个人的例子,效果很好 - community.atlassian.com/t5/Answers-Developer-Questions/…。如果他做了不同的事情,你可以环顾四周。
-
啊...不要隐藏您的
data... 当使用data=或json=时,给它dict对象 - 不是 JSONstr代表... -
谢谢@droravr。这实际上是我用作脚本的起点。只是为了确保,我只是从您提供的链接中获取了他的原始代码并再次运行它。我对他的代码也有同样的问题。
-
@davfive
requests.put(url, auth=self.m_auth, json=data)data是您的数据字典而不是 JSON 字符串有效吗? -
请不要编辑问题以将其标记为“已解决”。发布实际答案并将其标记为已接受。
标签: python python-requests confluence-rest-api