简体   繁体   English

将PHP卷曲转换为Python

[英]Convert PHP Curl To Python

I've been trying to translate some PHP code to Python 3 but can't quite get it to work. 我一直在尝试将一些PHP代码转换为Python 3,但无法完全正常工作。 In PHP I have the following: 在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";

I tried converting it to the following in Python: 我尝试在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()

But I get the following error: 但是我收到以下错误:

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

How can I correct this, or is there a more pythonic solution? 我该如何纠正呢,还是有更多的pythonic解决方案?

If anyone is interested in the solution, I came up with the following which worked: 如果有人对解决方案感兴趣,我想出了以下可行的方法:

    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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM