首页 > 解决方案 > php curl请求的python版本

问题描述

我想在 python 中测试一个 API,但我是一个在 python 中使用 api 的初学者,我根本不知道 PHP,如何获取 auth 密钥的示例在 php 中。我发现的所有东西都对我不起作用,有错误或 401 请求。所以我想问我有人可以帮我把它翻译成python请求吗?

<?php

function getAccessToken(): String
{
    $authUrl = "https://allegro.pl.allegrosandbox.pl/auth/oauth/token?grant_type=client_credentials";
    $clientId = "...";
    $clientSecret = "...";

    $ch = curl_init($authUrl);

    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($ch, CURLOPT_USERNAME, $clientId);
    curl_setopt($ch, CURLOPT_PASSWORD, $clientSecret);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    $tokenResult = curl_exec($ch);
    $resultCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($tokenResult === false || $resultCode !== 200) {
        exit ("Something went wrong");
    }

    $tokenObject = json_decode($tokenResult);

    return $tokenObject->access_token;
}

function main()
{
    echo "access_token = ", getAccessToken();
}

main();

标签: pythonphp

解决方案


Python 易于学习且使用起来令人兴奋。这是翻译:

import requests

def getAccessToken():
    authUrl = "https://allegro.pl.allegrosandbox.pl/auth/oauth/token?grant_type=client_credentials"
    clientId = "..."
    clientSecret = "..."

    tokenResult = requests.post(authUrl, auth=(clientId, clientSecret))
    resultCode = tokenResult.status_code


    if resultCode != 200:
        print("something went wrong")
        exit (1)

    tokenObject = tokenResult.json()

    return tokenObject['access_token']

def main():
    print("access_token = {}".format(getAccessToken()))

main()

让我知道它是否有效。如果是,请接受答案。


推荐阅读