我正在使用Google API。我以this为起点,here是实际的Python代码。
我已经在https://console.developers.google.com/apis/credentials创建了一个OAuth 2.0客户端ID,并以client_secret.json
的形式下载了它,该代码在代码中的使用如下:
CLIENT_SECRETS_FILE = "client_secret.json"
def get_authenticated_service():
flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES)
credentials = flow.run_console()
return build(API_SERVICE_NAME, API_VERSION, credentials = credentials)
client_secret.json
的内容如下:
{
"installed": {
"client_id": "**REDACTED**",
"project_id": "api-project-1014650230452",
"auth_uri": "https:\/\/accounts.google.com\/o\/oauth2\/auth",
"token_uri": "https:\/\/accounts.google.com\/o\/oauth2\/token",
"auth_provider_x509_cert_url": "https:\/\/www.googleapis.com\/oauth2\/v1\/certs",
"client_secret": "**REDACTED**",
"redirect_uris": [
"urn:ietf:wg:oauth:2.0:oob",
"http:\/\/localhost"
]
}
}
整个程序可以正常工作并成功返回有意义的数据集,但是,每次运行该程序时,都会提示如下:
Please visit this URL to authorize this application: https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=... Enter the authorization code:
我输入了代码,程序正常运行,但是每次程序运行时,我都必须访问此URL并获取新的代码。我的印象是client_secret.json
的存在正是为了防止这种情况的发生。
要使我的CLI Python程序使用API而又不必每次都获得新的令牌,该怎么办?
答案 0 :(得分:3)
您要运行脚本而不每次都检索代码。如果我的理解是正确的,那么该修改如何?在此修改中,首次运行脚本时,刷新令牌将保存到文件“ credential_sample.json”。这样,在下一次运行中,您可以使用由刷新令牌检索到的访问令牌使用API。因此,您不必每次都检索代码。
请进行如下修改。
来自:def get_authenticated_service():
flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES)
credentials = flow.run_console()
return build(API_SERVICE_NAME, API_VERSION, credentials = credentials)
至 :
from oauth2client import client # Added
from oauth2client import tools # Added
from oauth2client.file import Storage # Added
def get_authenticated_service(): # Modified
credential_path = os.path.join('./', 'credential_sample.json')
store = Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(CLIENT_SECRETS_FILE, SCOPES)
credentials = tools.run_flow(flow, store)
return build(API_SERVICE_NAME, API_VERSION, credentials=credentials)
如果这不是您想要的,对不起。