重用requests_oauthlib授权

时间:2018-01-06 16:21:34

标签: python oauth-2.0 python-requests authorization

我正在尝试使用requests_oauthlib从我的恒温器API获取数据。 API使用OAuth 2.我已经成功获取了第一块数据,并希望做更多。但是,目前,我的程序在每次运行时都会重复授权对话。我可能在文档中遗漏了一些东西,但是我可以重用收到的session.authorization_token(直到用户撤销恒温器网站上的授权)?

程序如下:

import json
from requests_oauthlib import OAuth2Session

client_id = r'api-XXXX'
client_secret = r'YYYY'

authorization_base_url = 'https://api.thermosmart.com/oauth2/authorize'
token_url = 'https://api.thermosmart.com/oauth2/token'
redirect_uri = 'https://google.com/'

session = OAuth2Session(client_id, redirect_uri=redirect_uri)

authorization_url, state = session.authorization_url(authorization_base_url)
print('Please go here and authorize: ', authorization_url)

# Get the authorization verifier code from the callback url
redirect_response = input('Paste the full redirect URL here and add a trailing space: ')
redirect_response = redirect_response[0:-1]  # prevent PyCharm from opening URL

# Fetch the access token
session.fetch_token(token_url, client_secret=client_secret,
                    authorization_response=redirect_response)

# Fetch a protected resource
r = session.get('https://api.thermosmart.com/thermostat')
if not r.status_code == 200:
    print("Not OK received")
else:
    thermostat_id = json.loads(r.content).get('hw')
    ...

1 个答案:

答案 0 :(得分:2)

您可以保存并重复使用令牌,但它们最终会过期。您需要配置刷新令牌的方法。请参阅:http://requests-oauthlib.readthedocs.io/en/latest/oauth2_workflow.html#refreshing-tokens

要回答有关如何重复使用它的问题,请执行以下操作:

new_session = OAuth2Session(client_id, token=variable_where_token_was_stored)
new_session.get('https://api.thermosmart.com/thermostat')