如何指定python请求http put body?

ome*_*ach 29 python http put httplib2 python-requests

我正在尝试使用requests模块重写一些旧的python代码.目的是上传附件.邮件服务器需要以下规范:

https://api.elasticemail.com/attachments/upload?username=yourusername&api_key=yourapikey&file=yourfilename
Run Code Online (Sandbox Code Playgroud)

有效的旧代码:

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'} )
Run Code Online (Sandbox Code Playgroud)

没有找到如何在请求中使用正文部分.

我设法做了以下事情:

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

但不知道如何使用文件内容指定正文部分.

谢谢你的帮助.奥马尔.

rab*_*ben 57

引用文档

data - (可选)在Request主体中发送的字典或字节.

所以这应该工作(没有测试):

 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}
                 )
Run Code Online (Sandbox Code Playgroud)

  • 这对我不起作用(Python 3.8)。我需要使用“json”而不是“数据”。请参阅下面的答案。 (5认同)

Ash*_*faq 11

我使用 Python 完成了这件事,它是请求模块。有了这个,我们可以提供一个文件内容作为页面输入值。看下面的代码,

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())
Run Code Online (Sandbox Code Playgroud)

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


注意:在这种情况下,请求的主体将被传递给jsonkwarg。

  • 这有几点帮助:1)你需要传递“headers=headers”。2)您应该详细说明在这种情况下“json”kwarg 是主体这一事实。3)你在你的打印语句中混合了python 2和3!:) (2认同)