【问题标题】:Updating a webpage using python requests returning error response code 415使用 python 请求更新网页返回错误响应代码 415
【发布时间】:2021-07-18 00:40:09
【问题描述】:

我正在尝试通过 Python 请求模块更新 Atlassian Confluence 页面中已经存在的页面。我正在使用 requests.put() 方法发送 http 请求以更新我的页面。该页面已有标题“更新状态”。我正在尝试输入一行作为页面的内容。我直接从我尝试访问的网页的 rest/api/content... 输出中复制了 json 有效负载中的页面 ID 和其他信息。 注意:我已经能够通过 python requests.get 从网页访问信息,但我无法将信息发布到网页。

用于从有效网页访问信息的方法:

response = requests.get('https://confluence.ai.com/rest/api/content/525424594?expand=body.storage',
                        auth=HTTPBasicAuth('svc-Automation@ai.com', 'AIengineering1@ai')).json()

用于将信息更新到该页面的方法不起作用,因为响应是错误 415 的形式。

import requests
from requests.auth import HTTPBasicAuth
import json

url = "https://confluence.ai.com/rest/api/content/525424594"
payload =  {"id":"525424594","type":"page", "title":"new page-Update Status","space":{"key":"TST"},"body":{"storage":{"value": "<p>This is the updated text for the new page</p>","representation":"storage"}}, "version":{"number":2}}

result = requests.put(url, data=payload, auth=HTTPBasicAuth('svc-Automation@ai.com', 'AIengineering1@ai'))
print (result)

我猜测有效负载的格式不正确。有什么建议? 注意:此处显示的链接、用户名和密码均为虚构。

【问题讨论】:

    标签: python json python-requests httprequest http-status-code-415


    【解决方案1】:

    尝试使用“json”命名参数而不是“data”发送数据,因此请求模块会将application/json 设置为content-type 标头。

    result = requests.put(url, json=payload, auth=HTTPBasicAuth('svc-Automation@ai.com', 'AIengineering1@ai'))
    

    【讨论】:

    • 不起作用,因为我收到了新的错误响应 400
    • @Ashish 这取决于 API 实现,但按照惯例,如果您收到 400 错误而不是 415,这意味着您已经解决了内容类型问题。你能和我分享一下 result.content 吗?因为您遇到的新错误可能是由于(您发送的)有效负载与 API 期望的格式不匹配造成的。 API 可能已经向您发送了一个回复,其中提到了您的有效负载中的格式问题。 developer.mozilla.org/en-US/docs/Web/HTTP/Status/400
    • 确定内容提到:{"statusCode":400, "data":{"authorized":true, "valid":false, "allowedInReadOnlyMode":true, "errors can't change an现有页面的空间。", "args":[]}}], "successful":false}, "message":"无法更新类型的内容:类 com.atlassian.confluence.pages.Page with id 525424594", “原因”:“错误请求”}
    • 格式是否应该与我访问链接 confluence.ai.com/rest/api/content/525424594 时显示的格式相同。所以我只更新了应该更新我网页正文的存储值,但它说我没有得到的错误请求。
    • 这是原始问题所要求的另一个问题。我认为您应该将此答案标记为已接受的答案,因为您不再收到 415 错误。后续问题应该有自己的问题帖子meta.stackoverflow.com/questions/266767/…
    猜你喜欢
    • 1970-01-01
    • 2012-05-05
    • 1970-01-01
    • 1970-01-01
    • 2019-10-13
    • 2019-10-18
    • 1970-01-01
    • 2017-02-17
    • 1970-01-01
    相关资源
    最近更新 更多