从php curl到python urllib(上传API的问题)

从php curl到python urllib(上传API的问题),python,curl,urllib,Python,Curl,Urllib,我尝试将php api代码转换为python: 这是php代码: // 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 =

我尝试将php api代码转换为python:

这是php代码:

// 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; 
这是我的Python代码:

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

它上载了我的文件,但响应是错误的,因此我的python代码肯定有问题。但是我看不出我的错误。

您的问题在于这一行:
datei=open(file'rb')。read()
。对于上传文件的urllib2.Request,它需要一个实际的文件对象,因此行应该是:
datei=open(file,'rb')
open(…).read()
返回一个
str
而不是file对象。

使用多部分/表单数据编码上传文件没有简单的方法。 不过,您可以使用一些代码段:

[ [

更简单的方法是使用库。 我使用的一些好的库有:


  • 在尝试了很多机会之后,我使用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"
    

    什么错误?另外,我假设
    @.
    在PHP中格式化字符串,如果没有,它会做什么?
    CURLOPT_RETURNTRANSFER
    会做什么?是的,
    @.
    在本地文件上连接字符串,在python中,您正在读取文件并发送它。这是我真正能看到的唯一区别。@isbadawi对此表示抱歉。Tryi我想一下子做的太多了。谢谢你的建议。我会检查一下的。