将PHP Curl转换为Python

2024-04-20 12:24:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在尝试将一些PHP代码翻译成python3,但不能很好地让它工作。在PHP中,我有以下内容:

$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将其转换为以下内容:

^{pr2}$

但我得到了以下错误:

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

我怎样才能纠正这个问题,或者有一个更像Python的解决方案?在


Tags: tokentruedatarequestpasswordresultcurlarray
1条回答
网友
1楼 · 发布于 2024-04-20 12:24:52

如果有人对这个解决方案感兴趣,我想出了以下行之有效的方法:

    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

相关问题 更多 >