我的代码有什么问题?我正在尝试发送 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’对象不可调用”
我该如何使用此授权?
代码中的问题是您使用 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 工具的真实密码,并将“