我如何转换卷曲data=@文件名`到Python请求?

2024-04-19 03:01:20 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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`;

我想改用Pythonrequests模块。我尝试了以下Python代码:

^{pr2}$

但我总是得到“ERROR no data found in request”的响应。我该如何解决这个问题?在


Tags: 文件脚本dataapplicationcookiemywwwtype
2条回答

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)

这将生成如下请求:

^{pr2}$

请注意,在这个版本和您原来的curl命令中,该文件必须已经是URL编码的。在

首先用UTF-8解码你的URL。在

将头和文件放在一个JSON对象中,删除所有的数据。在

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

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)

相关问题 更多 >