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_POSTFIELDS, $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.
'@'.formats a string in PHP, if not, what does it do? What doesCURLOPT_RETURNTRANSFERdo?@.is concatenating a string on local file and in python your are reading as it is the file and sending it. It's the only difference I can really see.