【问题标题】:How to specify python requests http put body?如何指定python请求http put body?
【发布时间】:2012-08-03 16:21:07
【问题描述】:

我正在尝试使用 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'} )

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

我设法做到了以下几点:

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

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

感谢您的帮助。 奥马尔。

【问题讨论】:

    标签: python http put httplib2 python-requests


    【解决方案1】:

    引用docs

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

    【讨论】:

    • 这对我不起作用(Python 3.8)。我需要使用“json”而不是“数据”。请参阅下面的答案。
    【解决方案2】:

    我使用 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())
    

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


    NB:在这种情况下,请求的主体被传递给json kwarg。

    【讨论】:

    • 这有助于但有几点:1)你需要通过headers=headers。 2)您应该详细说明 json kwarg 在这种情况下是主体。 3)您在打印语句中混合了 python 2 和 3! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-27
    • 1970-01-01
    • 1970-01-01
    • 2014-08-19
    • 1970-01-01
    • 2014-09-25
    • 2014-02-27
    相关资源
    最近更新 更多