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

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

问题描述:

我从一个Perl脚本调用curl来发布文件:如何将`curl --data = @ filename`转换为Python请求?

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) 

但我总是得到响应“错误没有找到请求中的数据”。我怎样才能解决这个问题?

+0

为什么这个问题有一个Perl标签? – Borodin

+0

@Borodin卷曲片段来自perl脚本 – AlexN

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编码。

+0

这工作。谢谢!我无法接受它作为正确的答案,因为我没有足够的代表在这个网站上。 – AlexN

+0

@AlexN太棒了,很高兴它为你工作。您可以接受任何代表级别的答案,直到15日才能得到答复。请参阅[特权页面](http://stackoverflow.com/help/privileges)。 – ThisSuitIsBlackNot

第一个UTF-8解码您的URL。

将标题和文件放入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) 
+0

括号不对,应该在开始时有一个额外的括号: all_data = {{file ... 如果是这样,那么它会给出一个错误,说不可能的类型字典 – AlexN

+0

@Borodin在编辑代码时仍然会显示“不可用类型:字典” – AlexN

+0

在发布之前先尝试json.dumps(all_data)。 –