简体   繁体   中英

How can I convert `curl --data=@filename` to Python requests?

I'm calling curl from a Perl script to POST a file:

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

I want to use the Python requests module instead. I've tried the following Python code:

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)

But I always get the response "ERROR no data found in request." How can I fix this?

The files parameter encodes your file as a multipart message, which is not what you want. Use the data parameter instead:

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)

This generates a request like:

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

Note that in both this version and in your original curl command, the file must already be URL encoded.

First UTF-8 decode your URL.

Put headers and files in a JSON object, lesse all_data.

Now your code should look like this.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM