2016-04-20 36 views
0

我一直在尝试将一些PHP代码翻译成Python 3,但无法完全实现它的功能。在PHP中,我有以下:将PHP卷曲转换为Python

$request = "https://api.example.com/token"; 
$developerKey = "Basic VVVfdFdfsjkUIHDfdsjYTpMX3JQSDNJKSFQUkxCM0p0WWFpRklh"; 
$data = array('grant_type'=>'password', 
       'username'=>'name', 
       'password'=>'pass', 
       'scope'=>'2346323'); 
$cjconn = curl_init($request); 
curl_setopt($cjconn, CURLOPT_POST, TRUE); 
curl_setopt($cjconn, CURLOPT_HTTPHEADER, array('Authorization: '.$developerKey)); 
curl_setopt($cjconn, CURLOPT_SSL_VERIFYPEER, FALSE); 
curl_setopt($cjconn, CURLOPT_RETURNTRANSFER, TRUE); 
curl_setopt($cjconn, CURLOPT_POSTFIELDS,http_build_query($data)); 
$result = curl_exec($cjconn); 
curl_close($cjconn); 
$tokens = json_decode($result,true); 
$accesstoken = $tokens['access_token']; 
echo $accesstoken."\n"; 

我试图将其转换为在Python如下:

import pycurl, json 

url = 'https://api.example.com/token' 
data = json.dumps({"grant_type":"password", 
         "username":"name", 
         "password":"pass", 
         "scope":"2346323"}) 
key = 'Basic VVVfdFdfsjkUIHDfdsjYTpMX3JQSDNJKSFQUkxCM0p0WWFpRklh' 
c = pycurl.Curl() 
c.setopt(pycurl.URL,url) 
c.setopt(pycurl.HTTPHEADER,['Authorization: {}'.format(key)]) 
c.setopt(pycurl.POST,1) 
c.setopt(pycurl.POSTFIELDS,data) 
c.perform() 

,但我得到了以下错误:

<faultstring>String index out of range: -1</faultstring> 

我怎样才能解决这个,还是有更多的pythonic解决方案?

+1

我想询问什么,我做错了。我试图解决在SO上多次提出的问题,因此显然没有很好的文档记录。 – user2694306

回答

1

如果有人有兴趣的解决方案,我想出了哪些工作如下:

def getToken(self): 
     """Retrieves the token from provider""" 
     #The data to be passed to retrieve the token 
     tokenData = {'grant_type':'password', 
        'username':TOKENUSERNAME, 
        'password':TOKENPASSWORD, 
        'scope':TOKENSCOPE} 
     #The header parameters 
     header_params = {'Authorization':KEY} 

     #Make the request for the token 
     r = requests.post(TOKENURL,data=tokenData,headers=header_params) 
     #Check the status code 
     if r.status_code not in [200,203]: 
      self.log.logentry("There was an error retrieving the data from Linkshare: {}:{}".format(r.status_code,r.text)) 
      sys.exit() 
     #Extract the data from the response 
     data = r.json() 
     #Parse the access token 
     token = {'token':data['access_token'], 
       'type':data['bearer']} 

     return token