python - 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();
解决方案
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()
让我知道它是否有效。如果是,请接受答案。
推荐阅读
- firebase - 让我的 Firebase 应用程序专门触发微服务
- razor - 是否可以更改每个 Razor 组件的 RenderMode?
- javascript - 在 Ace 编辑器中隐藏行
- maven - 由于不满足的依赖关系,某些插件无法加载。修复这些问题并重新启动 Jenkins 以重新启用这些插件
- docker - 主机硬重启后 Docker 服务不启动
- python - 在 BeautifulSoup/Selenium Scraper 中使用部分匹配
- oracle - 使用哈希 SHA-256
- java - 为什么 UDP 服务器的 Javafx GUI 停止工作
- c# - 如何在 .NET 中使用 CQRS 模式 mediatr 使 EF 事务化?
- javascript - Vue.js:从另一个组件调用方法