from php curl to python urllib (POST to Upload API Problem)
I tried to convert a php api code to python:
This is the php code:
// Variables to Post
$local_file = "/path/to/file";
$file_to_upload = array(
'file'=>'@'.$local_file,
'convert'=>'1',
'user'=>'YOUR_USERNAME',
'password'=>'YOUR_PASSWORD'
);
// Do Curl Request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'http://example.org/dapi.php');
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIEL开发者_如何学GoDS, $file_to_upload);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result=curl_exec ($ch);
curl_close ($ch);
// Do Stuff with Results
echo $result;
And this is my Python Code:
url = 'http://example.org/dapi.php'
file ='/path/to/file'
datei= open(file, 'rb').read()
values = {'file' : datei ,
'user' : 'username',
'password' : '12345' ,
'convert': '1'}
data = urllib.urlencode(values)
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
the_page = response.read()
print the_page
It uploads my files but the response is an Error so that something has to be wrong with my python code. But I can´t see my mistake.
After trying a lot of opportunities. I found my solution using pycurl:
import pycurl
import cStringIO
url = 'http://example.org/dapi.php'
file ='/path/to/file'
print "Start"
response = cStringIO.StringIO()
c = pycurl.Curl()
values = [('file' , (c.FORM_FILE, file)),
('user' , 'username'),
('password' , 'password'),
('convert', '1')]
c.setopt(c.POST, 1)
c.setopt(c.URL,url)
c.setopt(c.HTTPPOST, values)
#c.setopt(c.VERBOSE, 1)
c.setopt(c.WRITEFUNCTION, response.write)
c.perform()
c.close()
print response.getvalue()
print "All done"
There is no simple way to upload a file using multipart/form-data encoding. There are some snippets you can use, though:
[http://pymotw.com/2/urllib2/index.html#module-urllib2] [http://code.activestate.com/recipes/146306-http-client-to-post-using-multipartform-data/]
A simpler way would be to use a library. Some good libraries that I use are:
- requests
- mechanize
Your issue is with this line: datei= open(file, 'rb').read()
. For urllib2.Request to upload a file, it needs an actual file object, so the line should be: datei= open(file, 'rb')
. open(...).read()
returns a str
instead of the file object.
精彩评论