如何存储Oath2令牌以避免每次运行程序时都征求用户同意

时间:2019-05-04 03:29:45

标签: oauth-2.0 gspread

创建一个希望通过gspread访问用户的Google表格的Python程序。但是,每次运行该程序时,它都会询问用户是否有权访问其Google帐户。

我想知道是否有可能,以及如何存储程序收到的令牌,以便将来程序的使用不会每次都再次提示它们。

我已经花了几个小时来解决这个问题的解决方案,该问题都使用客户端ID而不是服务帐户(因此程序始终访问用户的Google帐户,而不是全局共享的帐户),并且可以连接到没有任何运气。

我假设我想要的是可能的,因为python的Google Sheets API快速入门指南具有我想要的确切行为,除了我不知道如何将其连接到gspread(这是该项目的必需库)之外。

我目前拥有的作品:


#Import libraries
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.tools import run_flow, argparser
from oauth2client.file import Storage
from oauth2client.client import AccessTokenCredentials
import requests
import gspread, ast

#Setup Oauth2
CLIENT_ID = '<Client ID>'
CLIENT_SECRET = '<Client Secret>'
flow = OAuth2WebServerFlow(client_id=CLIENT_ID,
                           client_secret=CLIENT_SECRET,
                           scope='https://spreadsheets.google.com/feeds',
                           redirect_uri='http://localhost:8080/')
storage = Storage('mycredentials.data')


credentials = run_flow(flow, storage, argparser.parse_args([]))

#Attempt login

data = {
    'refresh_token' : credentials.refresh_token,
    'client_id' : credentials.client_id,
    'client_secret' : credentials.client_secret,
    'grant_type' : 'refresh_token',
}
r = requests.post('https://accounts.google.com/o/oauth2/token', data = data)

credentials.access_token = ast.literal_eval(r.text)['access_token']

gc = gspread.authorize(credentials)

但是,如前所述,每次运行时都会询问用户许可,我希望它“保存”该许可以避免将来运行。

0 个答案:

没有答案