如何将`curl --data = @ filename`转换为Python请求?

时间:2017-02-28 11:00:59

标签: python curl python-requests

我从Perl脚本调用curl来POST一个文件:

my $cookie = 'Cookie: _appwebSessionId_=' . $sessionid;
my $reply  = `curl -s
                   -H "Content-type:application/x-www-form-urlencoded"
                   -H "$cookie"
                   --data \@portports.txt
                   http://$ipaddr/remote_api.esp`;

我想使用Python requests模块。我尝试过以下Python代码:

files = {'file': ('portports.txt', open('portports.txt', 'rb'))}
headers = {
    'Content-type' : 'application/x-www-form-urlencoded',
    'Cookie' : '_appwebSessionId_=%s' % sessionid
}

r = requests.post('http://%s/remote_api.esp' % ip, headers=headers, files=files)    
print(r.text)

但我总是得到回复" ERROR没有在请求中找到数据。"我该如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

files参数将您的文件编码为多部分邮件,这不是您想要的。请改用data参数:

import requests

url = 'http://www.example.com/'
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
cookies = {'_appwebSessionId_': '1234'}

with open('foo', 'rb') as file:
    response = requests.post(url, headers=headers, data=file, cookies=cookies)
    print(response.text)

这会生成如下请求:

POST / HTTP/1.1
Connection: keep-alive
Accept: */*
Accept-Encoding: gzip, deflate
Host: www.example.com
User-Agent: python-requests/2.13.0
Content-Length: 15
Content-Type: application/x-www-form-urlencoded
Cookie: _appwebSessionId_=1234

content of foo

请注意,在此版本和原始curl命令中,该文件必须已经过URL编码。

答案 1 :(得分:-1)

首先UTF-8解码您的网址。

将标题和文件放在JSON对象中,减少all_data。

现在你的代码应该是这样的。

all_data = {
    {
        'file': ('portports.txt', open('portports.txt', 'rb'))
    },
    {
        'Content-type' : 'application/x-www-form-urlencoded',
        'Cookie' : '_appwebSessionId_=%s' % sessionid
    }
}


all_data = json.dumps(all_data)
requests.post(url, data = all_data)