2016-04-20 35 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