雅虎API - 当之前的访问令牌过期时,无法请求新的访问令牌。

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

我正试图使用雅虎的API来制作梦幻足球,我一开始能够收到访问令牌和刷新令牌,但一旦该访问令牌过期,我就无法获得另一个令牌。我能够收到一个访问令牌和刷新令牌,但一旦该访问令牌过期,我就无法获得另一个令牌。

我的代码如下。

from requests import Request, get, post
import webbrowser
import base64

baseURL = 'https://api.login.yahoo.com/'
oauthENDPOINT = "https://api.login.yahoo.com/oauth2/request_auth"


## Generate a url using the endpoint and parameters above
params = {'client_id' : client_id,
          'redirect_uri' : "oob",
          'response_type' : 'code'}
p = Request('GET', oauthENDPOINT, params=params).prepare()

webbrowser.open(p.url)

最后一行将我发送到雅虎网站 我在那里允许自己访问并接收到了 authCode.

encoded = base64.b64encode((client_id + ':' + client_secret).encode("utf-8"))
headers = {
    'Authorization': f'Basic {encoded.decode("utf-8")}',
    'Content-Type': 'application/x-www-form-urlencoded'
}
data = {
    'grant_type': 'authorization_code',
    'redirect_uri': 'oob',
    'code': authCode}

tokenResponse = post(baseURL + 'oauth2/get_token', headers=headers, data=data)
tokenResponseJSON = tokenResponse.json()
access_token = tokenResponseJSON['access_token']
refresh_token = tokenResponseJSON['refresh_token']

我现在有所有必要的信息来检查我的联盟的设置(例如)。

fbURL = 'https://fantasysports.yahooapis.com/fantasy/v2'

leagueURL1 = f'{fbURL}/leagues;league_keys=nfl.l.{leagueID}/settings'

headers = {
    'Authorization': f'Bearer {access_token}',
    'Accept': 'application/json',
    'Content-Type': 'application/json'
}

response2 = get(leagueURL1, headers=headers,params={'format': 'json'})

上面的工作和预期的一样。然而, access_token 持续3600秒,一旦时间过了,我就无法再申请新的,用我的 refresh_token. 我的尝试。

accessTokenData = {
    'grant_type': 'refresh_token',
    'redirect_uri': 'oob',
    'code': authCode,
    'refresh_token': refresh_token
}

accessTokenResponse = post(baseURL + 'oauth2/get_token', headers=headers, data=accessTokenData)
accessTokenJSON = accessTokenResponse.json()

在上面,我希望收到一个新的... access_token而不是 accessTokenJSON 是这样的。

{'error': {'localizedMessage': 'client request is not acceptable or not supported',
  'errorId': 'INVALID_INPUT',
  'message': 'client request is not acceptable or not supported'}}

到目前为止,我一直在关注 这些步骤到现在为止都很好用 我到底做错了什么?我知道许多 Python 用户使用 yahoo_oauthrauth 用于认证,但这涉及到保存 client_idclient_secret 在...中 .json 文件,我想动态加载这些文件。我想我离成功已经不远了,但在生成一个新的 refresh_token. 所有的帮助非常感谢!

python-3.x python-requests yahoo-api
1个回答
1
投票

感谢参考我们的指南。

我设法重现了你的错误,解决起来非常简单。

你正在重新定义 headers 变量在你的请求中的fantasyspot url。

headers 变量应该在请求新的 access_token 使用 refresh_token 就像最初使用的时候,用的是 auth_code.

所以只要定义 header 在申请新的 access_token. 应该是下面这个样子。

headers = {
    'Authorization': f'Basic {encoded.decode("utf-8")}',
    'Content-Type': 'application/x-www-form-urlencoded'
}
response = post(base_url + 'oauth2/get_token', headers=headers, data=data)

现在应该可以了。

建议对这些变量使用不同的名称。headers 惯用 access_token 以及用于奇幻城娱乐体育网址的那个。

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