如何指定Python requests的HTTP PUT请求体?

65

我正在尝试使用requests模块重新编写一些旧的Python代码,目的是上传附件。邮件服务器要求进行以下规定:

https://api.elasticemail.com/attachments/upload?username=yourusername&api_key=yourapikey&file=yourfilename

能够工作的旧代码:

h = httplib2.Http()        
        resp, content = h.request('https://api.elasticemail.com/attachments/upload?username=omer&api_key=b01ad0ce&file=tmp.txt', 
        "PUT", body=file(filepath).read(), 
        headers={'content-type':'text/plain'} )

我找不到如何在请求中使用body部分。

我成功完成了以下操作:

 response = requests.put('https://api.elasticemail.com/attachments/upload',
                    data={"file":filepath},                         
                     auth=('omer', 'b01ad0ce')                  
                     )

但是我不知道如何使用文件内容指定请求体。

谢谢您的帮助。 Omer.

2个回答

95

引用自文档

data – (可选)要发送到请求体中的字典或字节。

因此,这个代码应该可以工作(未经测试):

 filepath = 'yourfilename.txt'
 with open(filepath) as fh:
     mydata = fh.read()
     response = requests.put('https://api.elasticemail.com/attachments/upload',
                data=mydata,                         
                auth=('omer', 'b01ad0ce'),
                headers={'content-type':'text/plain'},
                params={'file': filepath}
                 )

5
对我来说这不起作用(Python 3.8)。我需要使用'json'而不是'data'。请参见下面的答案。 - VectorVictor

20

我用Python和request模块使这个东西工作了。我们可以将文件内容作为页面输入值提供。请参见下面的代码:

import json
import requests

url = 'https://Client.atlassian.net/wiki/rest/api/content/87440'
headers = {'Content-Type': "application/json", 'Accept': "application/json"}
f = open("file.html", "r")
html = f.read()

data={}
data['id'] = "87440"
data['type']="page"
data['title']="Data Page"
data['space']={"key":"AB"}
data['body'] = {"storage":{"representation":"storage"}}
data['version']={"number":4}

print(data)

data['body']['storage']['value'] = html

print(data)

res = requests.put(url, json=data, headers=headers, auth=('Username', 'Password'))

print(res.status_code)
print(res.raise_for_status())

如果您有任何疑问,请随时提出。


NB:在此情况下,请求的主体被传递到json关键字参数中。


2
这有所帮助,但需要注意几点:1)您需要传递headers=headers。2)您应该详细说明在这种情况下json关键字参数是请求正文。3)您在打印语句中混合使用了Python 2和3!! :) - Little Bobby Tables

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接