如何指定python请求http put body? [英] How to specify python requests http put body?

查看:535
本文介绍了如何指定python请求http put body?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to rewrite some old python code with requests module. The purpose is to upload an attachment. The mail server requires the following specification :

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'} )

未找到如何在请求中使用正文部分。

Didn't find how to use the body part in requests.

我设法做了以下事情:

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

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

But have no idea how to specify the body part with the content of the file.

感谢您的帮助。
Omer。

Thanks for your help. Omer.

推荐答案

引自 docs


数据 - (可选)要在请求的正文中发送的字典或字节。

data – (optional) Dictionary or bytes to send in the body of the Request.

所以这个应该工作(未测试):

So this should work (not tested):

 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}
                 )

这篇关于如何指定python请求http put body?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆