2016-04-20 19 views
0

Ich habe versucht, einige PHP-Code in Python 3 zu übersetzen, aber es kann nicht ganz funktionieren. In PHP habe ich folgende:Convert PHP Curl zu 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"; 

Ich habe versucht, es zu der Umwandlung folgend in 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() 

Aber ich erhalte die folgenden Fehler:

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

Wie kann ich dies korrigieren oder gibt es eine mehr pythische Lösung?

+1

Ich versuche, zu fragen, was ich falsch mache. Ich habe versucht, ein Problem zu lösen, das mehrfach auf SO gestellt wird, also ist es eindeutig nicht gut dokumentiert. – user2694306

Antwort

1

Wenn jemand Interesse an der Lösung ist, kam ich mit dem Follow-up, die gearbeitet:

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