使用 Python 请求将附件上传到 Confluence REST API 会出现 415 和 500 错误

Arn*_*rtz 6 python rest python-requests confluence-rest-api

我正在尝试使用 Python 请求通过 REST API 将附件上传到 Confluence。我总是收到“415 不支持的媒体类型”错误或“500 内部服务器错误”,具体取决于我发送请求的方式。

有一些信息介绍了如何使用其他语言执行此操作,或者通过现已弃用的 XMLRPC API 使用 Python,或者针对行为似乎略有不同的 JIRA REST API。

根据所有这些信息,代码应该如下所示:

def upload_image():
    url = 'https://example.com/confluence/rest/api/content/' + \
          str(PAGE_ID) + '/child/attachment/'
    headers = {'X-Atlassian-Token': 'no-check'}
    files = {'file': open('image.jpg', 'rb')}
    auth = ('USR', 'PWD')
    r = requests.post(url, headers=headers, files=files, auth=auth)
    r.raise_for_status()
Run Code Online (Sandbox Code Playgroud)

缺少的是正确的内容类型标头。那里有不同的信息:

  • 在本例中,为文件使用正确的内容类型image/jpeg
  • 使用application/octet-stream
  • 使用application/json
  • 使用multipart/form-data

(我使用的Confluence版本是5.8.10)

Arn*_*rtz 7

使用正确的内容类型并不是这里唯一的问题。在正确的地方使用它同样重要。对于文件上传,内容类型必须与文件一起提供,而不是作为请求本身的标头。

尽管Python 请求文档明确写道该files参数用于上传多部分编码的文件,但内容类型需要显式设置为附件的正确类型。
虽然它并不完全正确(请参阅下面的评论),但multipart/form-data也可以工作,因此如果我们确实无法确定正确的内容类型,我们可以使用它作为后备:

def upload_image():
    url = 'https://example.com/confluence/rest/api/content/' + \
          str(PAGE_ID) + '/child/attachment/'
    headers = {'X-Atlassian-Token': 'no-check'} #no content-type here!
    file = 'image.jpg'

    # determine content-type
    content_type, encoding = mimetypes.guess_type(file)
    if content_type is None:
        content_type = 'multipart/form-data'

    # provide content-type explicitly
    files = {'file': (file, open(file, 'rb'), content_type)}

    auth = ('USR', 'PWD')
    r = requests.post(url, headers=headers, files=files, auth=auth)
    r.raise_for_status()
Run Code Online (Sandbox Code Playgroud)