如何使用 OAuth2 与请求 get

问题描述 投票:0回答:1

我的代码有什么问题?我正在尝试发送 API 请求并收到错误:

“OAuth2Session”对象不可调用

import requests
from oauthlib.oauth2 import BackendApplicationClient
from requests_oauthlib import OAuth2Session
client_id = '111'
username = '222'
password = '333'
client = BackendApplicationClient(client_id=client_id)
oauth = OAuth2Session(client=client)
headers = {

    'Content-type': 'application/json',
    'Authorization': 'Bearer <token>'
}
url = "https://<API datasourse>"
response = requests.get(
     url,
    auth=oauth,
    headers=headers,
    verify=False
)
print(response.json())`

我正在尝试发送 API 请求并收到错误:

“‘OAuth2Session’对象不可调用”

我该如何使用此授权?

python oauth-2.0 python-requests typeerror
1个回答
0
投票

代码中的问题是您使用 OAuth2Session 对象,就好像它是一个函数一样,这导致了错误。相反,您应该在发出 API 请求之前使用 fetch_token 方法获取访问令牌。

以下代码应该可以工作:

import requests
from oauthlib.oauth2 import BackendApplicationClient
from requests_oauthlib import OAuth2Session

client_id = '111'
client_secret = 'your_client_secret'  # Don't hardcode this, use a secure method to store it
token_url = 'https://<token_endpoint>'  # Replace with the actual token endpoint URL

client = BackendApplicationClient(client_id=client_id)
oauth = OAuth2Session(client=client)
token = oauth.fetch_token(token_url=token_url, client_id=client_id, client_secret=client_secret)

headers = {
    'Content-type': 'application/json',
    'Authorization': f'Bearer {token["access_token"]}'
}

url = "https://<API_datasource>"
response = requests.get(url, headers=headers, verify=False)

print(response.json())

请务必将“your_client_secret”更改为您的 OAuth2 工具的真实密码,并将“”切换为您获取令牌的实际位置。另外,请考虑确保秘密信息的安全,例如您的客户代码。 此代码使用 fetch_token 操作获取访问通行证,然后使用“授权”标签将其放入 API 请求的标头中。

© www.soinside.com 2019 - 2024. All rights reserved.